是否可以在没有await关键字的情况下调用异步函数?如果我们不等待就打电话怎么办?

Iqb*_*Jan 5 javascript reactjs react-native google-cloud-firestore

我想做以下事情,并记住它实际上对我有用。我的问题是怎么回事,可以async usrs()从非异步componentDidMount()函数中调用函数吗?如果不可能,为什么打电话给我this.usrs(usrs)而不是对我有用await this.usrs(usrs);

let outState = {};
class A extends Component{
  componentDidMount(){
   this.usrs(usrs);
  }
  getData(usr){
    return db.collection('a/'+usr+'/bb').get().then(snap=>{
      for(i = snap.docs.length-1; i>=0; i--){
         outState[usr] = [...outState[usr], snap.docs[i].data()];
         if(i === 0) return outState;
      }
     return false;
    });
  }

  async usrs(usrs){

   let os = {}, data = {};

    for(i = usrs.length-1; i>=0; i--){

       os = await this.getData(usrs[i]);
       if(os){
          data = { ...data, ...os };
          if (i === 0) {
             this.setState({ ...this.state, ...data });
          }
       }

    }

  }

}
Run Code Online (Sandbox Code Playgroud)

SiS*_*iSa 7

我们await在需要调用并等待async函数时使用,或者Promise
在您的情况下,当您在没有await内部的情况下调用它时componentDidMount,您的函数将起作用,但您componentDidMount不会等待该函数完全完成。
此外,如果您不想使用await,也不想在里面等待componentDidMount,但希望在async函数完成时得到通知,则可以.then改用。因为async函数返回Promise

这是您的componentDidMountwith.then
注意,在此示例this.doSomethingElse中将在this.usrs完成之前调用,并且只有在完成时才会在内部通知.thenthis.usrs结果:

componentDidMount(){
    this.usrs(usrs).then(() => {
        // Your functions completely finished
    })
    .catch(err => {
        // There was an error
    });

    this.doSomethingElse();
}
Run Code Online (Sandbox Code Playgroud)


Gol*_*rol 6

await在调用方需要等待函数完成时才需要,例如,当它需要函数结果时,或者当它需要等待函数导致的某些状态/数据更改时。如果没有这种依赖性,则可以不使用await关键字而“解雇” 。

正如其他人提到的那样,您也可以使用.then,但是基本规则是相同的:您可以在函数完成后有特定的事情要做时这样做。否则可以省略。

具体来说:对于“调用方”,我只是指调用异步函数的函数。在你的情况下componentDidMount。选项非常简单:

  1. 保持原样。usrs()将完全在后台componentDidMount运行,并将继续运行直到结束。
  2. 使用await,因此componentDidMount将等待的返回usrs()
  3. 使用usrs().then(),因此componentDidMount可以继续,但是如果需要完成.then()之后usrs()必须执行的操作,则在返回后将调用中指定的代码usrs()