【问题标题】:sequencing async/await calls in TypeScript在 TypeScript 中对 async/await 调用进行排序
【发布时间】:2020-07-20 17:08:06
【问题描述】:

我有以下代码 sn-p。我面临一个问题,有时序列不被遵守,即 _doSomethingNext( ) 在 _doSomethingFirst( ) 之前调用。

<CustomModal
  onDissmiss( ): { ( )=> { 
     executeInSequence( );
  }
}
/>
private executeInSequence( ):void {
   this._fun1( ).then(( ) => { this._fun2(); });
} 
private async _fun1( ):void {
  const result: IResultArray[] = await httpClient1.getData ();
    if (!result) {
        this._doSomethingFirst();
    }
}
private async _fun2( ):void {
  const result: IResultArray[] = await httpClient2.getData ();
    if (!result) {
        this._doSomethingNext();
    }
}

知道为什么会发生这种情况,我如何确保顺序和只有一次调用等待 getData() 调用。

【问题讨论】:

  • 可能是因为您没有从_fun1_fun2 返回任何内容?
  • _fun1 和 _fun2 也需要是 async 函数才能使用 await 关键字
  • @AluanHaddad 这绝对是真的。您不能在未声明为async 的函数内使用await 关键字,因为它会导致语法错误。我不确定您从哪里获得信息,但请阅读更多内容
  • 对不起,我误读了您的评论。出于某种原因,我以为您是在说只能等待异步函数
  • @AluanHaddad 这更有意义,很抱歉如此严厉地回应,但如果有人读到它然后开始尝试在未声明为 async 的函数中使用 await 那就不好了

标签: reactjs typescript async-await ecmascript-2016


【解决方案1】:

你应该有这样的 return 语句和 async 关键字;

private async _fun1( ) {
  const result: IResultArray[] = await httpClient1.getData ();
    if (!result) {
        return this._doSomethingFirst();
    }
}

private async _fun2( ) {
  const result: IResultArray[] = await httpClient2.getData ();
    if (!result) {
        return this._doSomethingNext();
    }
}


【讨论】:

  • 我假设代码 sn-p 是有效的,即使 fun1()、doSomethingFirst() 和 doSomethingNext() 都声明为 void 返回类型。
  • 我错过了@Tarun的void返回类型,我会改变
猜你喜欢
  • 2016-02-26
  • 2020-05-19
  • 2017-05-29
  • 2023-03-27
  • 2018-10-11
  • 2016-08-22
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
相关资源
最近更新 更多