【发布时间】:2021-01-19 05:12:28
【问题描述】:
我对承诺的解决感到困惑。如果我创建了一个承诺数组并为所有承诺提供了一个 .then() ,如下所示..
// assume async() returns a promise that resolves with the number 5.
promiseArray = [];
for (let i = 0; i < 5; i++){
promiseArray.push(async(5).then(() => console.log("done")));
}
Promise.all(promiseArray).then(() => console.log("all done"));
我对这里发生的事情感到困惑。承诺是否在 Promise.all() 完成之前就开始控制台记录“完成”? Promise.all() 的 .then() 是否是一个单独的 .then(),仅在所有承诺解决后才运行?
从所有单独的 Promise 中删除 .then() 并在 Promise.all() 的 .then() 中执行此代码有什么区别,如下所示?是否有任何性能权衡?
// assume async() returns a promise that resolves with the number 5.
promiseArray = [];
for (let i = 0; i < 5; i++){
promiseArray.push(async(5));
}
Promise.all(promiseArray).then((resolves) => resolves.forEach(console.log("done")));
【问题讨论】:
-
async函数是什么? -
我已经编辑了帖子,但只是说 async 返回了一个以数字 5 解析的承诺。这只是一个假设示例。
-
如果您对承诺的解决感到困惑,记录在案:Promise resolution procedure
标签: javascript asynchronous promise es6-promise