【问题标题】:Executing asynchronous functions in order, and waiting for for every function to be finished依次执行异步函数,等待每个函数执行完毕
【发布时间】:2021-10-28 14:14:48
【问题描述】:

我需要按特定顺序执行一些异步函数,并等待每个函数完成。 我是这样做的:

public async init(): Promise<void> {
try {
 this.executeFunction1().then(() => {
    this.executeFunction2().then(() => {
      this.executeFunction3().then(() => {
        this.executeFunction4().then(() => {
          this.executeFunction5();
        });
      });
    });
  });
} catch (error) {
  this.log.error(`Init failed`);
}

}

所有函数都是异步的:

  public async executeFunction1(): Promise<void> {
   ...........................
  }

这是一种好方法(最佳做法)还是这种方法是“好的”/“不建议”,但有更好的方法吗?

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    这是一个琐碎的async/await 案例。由于您已经在使用async,因此您缺少awaits。这样的事情会做:

    public async init(): Promise<void> {
        try {
            await this.executeFunction1();
            await this.executeFunction2();
            await this.executeFunction3();
            await this.executeFunction4();
            await this.executeFunction5();
        } catch (error) {
            this.log.error(`Init failed`);
        }
    }
    

    这种编程是引入async/await的主要原因,以促进以伪同步方式进行异步调用。

    【讨论】:

      【解决方案2】:

      如果你想使用RxJS你可以使用concat创建方法:

      import { concat } from 'rxjs';
      
      concat(
        this.executeFunction1(),
        this.executeFunction2(),
        this.executeFunction3(),
        this.executeFunction4(),
        this.executeFunction5(),
      ).subscribe();
      

      【讨论】:

        【解决方案3】:

        你可能想要这样的东西:

        public async init(): Promise<void> {
          try {
           await this.executeFunction1();
           await this.executeFunction2();
           // etc ...
          } catch (error) {
            this.log.error(`Init failed`);
          }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-30
          • 2017-12-30
          • 1970-01-01
          • 1970-01-01
          • 2020-10-30
          • 1970-01-01
          • 2015-09-16
          • 1970-01-01
          相关资源
          最近更新 更多