等待函数,但让它们同步,然后调用最后一个函数
Await functions but do them synchrony, then call the last function
所以我正在使用 Vue、Node 和打字稿。
我正在获取我所有其他功能都需要的数据,因此 getDataForFunction123()
需要一个 await 并且没问题。
然后我有 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();
}
我认为 Promise.all()
不能解决这个问题?因为它也在按顺序而不是在同一时间执行功能?正确的?这不会节省我的时间,但可以节省一些错误处理?
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();
}
所以我正在使用 Vue、Node 和打字稿。
我正在获取我所有其他功能都需要的数据,因此 getDataForFunction123()
需要一个 await 并且没问题。
然后我有 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();
}
我认为 Promise.all()
不能解决这个问题?因为它也在按顺序而不是在同一时间执行功能?正确的?这不会节省我的时间,但可以节省一些错误处理?
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();
}