Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何声明函数变量并等待它完成?_Javascript_Function_Asynchronous_Functional Programming_Async Await - Fatal编程技术网

Javascript 如何声明函数变量并等待它完成?

Javascript 如何声明函数变量并等待它完成?,javascript,function,asynchronous,functional-programming,async-await,Javascript,Function,Asynchronous,Functional Programming,Async Await,接下来,我想做一些长流程,然后在流程完成后设置我的状态 我正在执行以下例行程序: constructor(props) { super(props); let MyParameter = this.props.navigation.state.params.Whatever; getResults(MyParameter).then((response) => {this.setState({isLoading: false, result: response

接下来,我想做一些长流程,然后在流程完成后设置我的状态

我正在执行以下例行程序:

constructor(props) {
    super(props);

    let MyParameter = this.props.navigation.state.params.Whatever;

    getResults(MyParameter).then((response) => {this.setState({isLoading: false, result: response })});

    this.state = {
        isLoading: true,
        result: null,
        resultDS: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }),
    }
}

// ..

async getResults(parameter: Object)
{
    let finalResult = [];
    await var myfunc = function() { // Do the long process and populate finalResult}
    return finalResult;
}
我遵循了,但仍然出现错误:

上的意外标记等待var myfunc=function(){/*…*/}

我如何解决这个问题?

类似的问题

async getResults(parameter: Object)
{
  let finalResult = [];
  const myFunc = async function() { /* Do the long process and populate finalResult */ };

  await myFunc(); 
  return finalResult;
}
或者,一种更简洁的方法是让长时间运行的流程函数在完成后返回finalResult,这样,如果finalResult在myFunc之外不相关,就不必在getResults的范围内维护finalResult

async getResults(parameter: Object)
{
  const myFunc = async function() { /* Do the long process and return finalResult */ };
  return myFunc(); 
}
await
返回时的关键字与返回异步函数的异步函数是冗余的,因此没有必要


很重要的一点是,您的长时间运行的进程不会过早返回,因此,如果进程中的任何内容正在使用回调或异步,那么请确保适应这种情况

我认为你应该这样做:

var finalResult = await YOUR_FUNCTION_DOING_SOMETHING_LONG()
return finalResult.data // If response is an object.

但是你的
你的函数\u正在做某事\u LONG
应该返回一个承诺。

var myfunc=FUNCTION(){…}
声明一个函数。只有当您想等待一个异步函数完成时,您才使用
wait
,也就是说,您调用了一个函数。@MikeC有点像
var myFunc=function(){}
,然后
return await myFunc()
?为什么
return myFunc()有括号?只写
返回myFunc
会有区别吗?