等待函数但同步它们,然后调用最后一个函数

Joh*_*rén 1 javascript async-await vue.js es6-promise vue-component

所以我正在使用 Vue、Node 和 typescript。我正在获取我所有其他函数都需要的数据,因此getDataForFunction123()需要等待并且很好。

然后我有 3 个函数来获取不同的东西,而不是相互依赖。但是所有答案都被最后一个函数使用updateAfterFunction123IsDone()。但是当我像现在这样,我们需要等待功能 1、2 和 3 的同步。这需要很多时间。我想让函数 1、2 和 3 同时执行这些操作,但还想知道所有 3 项何时完成,然后调用updateAfterFunction123IsDone().

这是代码:

async initData () {
  await this.getDataForFunction123();

  await this.function1();
  await this.function2();
  await this.function3();

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

我不认为一个Promise.all()会解决这个问题?因为它也是按顺序执行功能而不是同时执行?对?这不会节省我的时间,但会为我节省一些错误处理?

Dan*_*Dan 5

Promise.all一旦它的所有承诺都得到解决,就会触发。所以运行你的所有函数function1, , function2,function3立即, 不await, 然后在他们的承诺得到解决后继续:

async initData () {
  await this.getDataForFunction123();

  const p1 = this.function1();
  const p2 = this.function2();
  const p3 = this.function3();

  await Promise.all([p1, p2, p3]);
  this.updateAfterFunction123IsDone();
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。这正是我一直在寻找的。我需要读一下 Promise.all 我看到的更多内容。谢谢! (2认同)