【问题标题】:synchronous execution of function after multiple asynchronous functions多个异步函数后同步执行函数
【发布时间】:2018-10-28 23:25:54
【问题描述】:

我有 3 个异步 typescript 方法,它们将被并行执行,如下所示。我想在他们三个都完成执行后执行最后一个函数。我怎么能陪这个。

this.getTimeLecs(prevTimeStartStr , nowTimeStartStr).then((result) => {
  // console.log(result);
  this.previousData = result;
});
this.getTimeLecs(nowTimeStartStr, nextTimeStartStr).then((result) =>{
  this.currentData = result;
});
this.getTimeLecs(nextTimeStartStr , nextTimeEnd ),then(result) => {
  this.nextData = result;
};
finalFunction();

【问题讨论】:

    标签: typescript asynchronous


    【解决方案1】:

    使用async/await可以实现。

    export class AsyncAwaitExample {
      constructor() {
      }
      getTimeLecs(str1, str2) {
        return Promise.resolve(str1 + ":" + str2).then(v => console.log(v));
      }
      async getTimeALL() {
        await Promise.all([
          this.getTimeLecs(10, 20),
          this.getTimeLecs(20, 30),
          this.getTimeLecs(30, 40)]
        );
        this.finalCall();
      }
      finalCall() {
        console.log('final call');
      }
    }
    
    let example = new AsyncAwaitExample();
    example.getTimeALL();
    

    这里

     await Promise.all([
              this.getTimeLecs(10, 20),
              this.getTimeLecs(20, 30),
              this.getTimeLecs(30, 40)]
            );
    

    等待所有的承诺得到解决,然后调用finalCall() 方法。 要检查这是否有效,请从上面的代码中删除 await 并在控制台中查看结果。检查Demo,看看它的实际效果。

    【讨论】:

    • 谢谢....有人请通过投票来给予他应有的信任
    【解决方案2】:

    我遇到过几次这种情况,一个非常简单的方法是在示波器顶部使用计数器。然后在每次回调时,递增计数器,如果它等于调用总数,则该函数已准备好被调用。

    但是,还有更迷人的方法,例如异步库,这要好得多,因为您可以添加更多功能而无需重新评估计数器和更改每个测试。

    【讨论】:

    • 感谢您的解决方案...但我更喜欢异步库中的解决方案
    猜你喜欢
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2021-07-16
    相关资源
    最近更新 更多