假设我有一堆 promise 。
const promises = [ /*...*/ ];
当所有的 promise 都已兑现时,我希望发生一些事情。以下两种方法之间的区别是什么:
使用
Promise.all
const allDonePromise = Promise.all(promises);
连续运行 promise
async function allPromises(promisesArray) { const results = []; for (const promise of promisesArray) { results.push(await promise); } return results; } const allDonePromises = allPromises(promises);
Promise.all
只是一个内置函数,它执行 allPromises
所做的事情,还是在幕后发生了其他事情以使 Promise.all 更快。我在哪里可以找到有关 Promise.all
内部结构的信息?
最佳答案
您可以找到 Promise.all
的规范在 section 25.4.4.1 of the ECMAScript 2015 Language Specification .
您自己的实现确实是在做正确的事情。区别在于细节:
上述规范在 25.4.4.1.1.r 点指出 then
是为每一个应许而被调用。这些调用是同步发生的(注意:不是它们的回调)。每当任何 promise 解决时,remainingElementsCount 都会递减(请参阅步骤 2.10)。每当它变为零时,Promise.all
返回的 promise 。已解决(注意:同步!)。
现在假设您有一个包含一百万个 promise 的数组,第一个 promise 花费的时间最长,那么您的函数在函数返回之前仍然需要执行 999999 等待,而规范中的算法已经处理了决议在第一个 promise 解决之前 有 999999 个 promise ,并且在第一个 promise 最终解决之后几乎没有什么可做的。
例如,您可以在 this polyfill/promise.js implementation 中看到这个(通过递增进行计数):
shaka.polyfill.Promise.all = function(others) { var p = new shaka.polyfill.Promise(); if (!others.length) { p.resolve_([]); return p; } // The array of results must be in the same order as the array of Promises // passed to all(). So we pre-allocate the array and keep a count of how // many have resolved. Only when all have resolved is the returned Promise // itself resolved. var count = 0; var values = new Array(others.length); var resolve = function(p, i, newValue) { shaka.asserts.assert(p.state_ != shaka.polyfill.Promise.State.RESOLVED); // If one of the Promises in the array was rejected, this Promise was // rejected and new values are ignored. In such a case, the values array // and its contents continue to be alive in memory until all of the Promises // in the array have completed. if (p.state_ == shaka.polyfill.Promise.State.PENDING) { values[i] = newValue; count++; if (count == values.length) { p.resolve_(values); } } }; var reject = p.reject_.bind(p); for (var i = 0; i < others.length; ++i) { if (others[i].then) { others[i].then(resolve.bind(null, p, i), reject); } else { resolve(p, i, others[i]); } } return p; };
但请注意,浏览器的实现各不相同。上面的 polyfill 只是其中一种可能的实现方式。
请注意,您的功能不是“连续运行 promise ”。无论您是否对它们执行某些操作, promise 都在“运行”*:它们会在您构建它们后立即执行它们的工作。
唯一被序列化的是您开始查看(即等待)相应的 promise 决议的时刻。规范似乎暗示实现应该从一开始就监听所有 promise 的解决回调。这不能用 await
实现在一个循环中(好吧,你可以,但是你需要重复调用 async
函数,每个 promise 一次,这不会给你带来任何好处使用 await
而不是 then
,因为你需要在 then
函数返回的 promise 上应用 async
。
然后在 this
的区域中还有一些其他(明显的)差异和参数验证。值得注意的是 ECMA 规范声明:
The
all
function requires itsthis
value to be a constructor function that supports the parameter conventions of thePromise
constructor.
* Promise 并不真正“运行”,因为 promises 是对象,而不是函数。可能正在运行的是一些在创建 promise 对象时启动的异步任务。 promise 构造函数回调可能会调用异步 API(如 setTimeout
、fetch
、...),这可能会导致异步调用 resolve
。 .最好将此中间状态称为“待定”(而不是“运行”)的 promise
关于javascript - Promise.all 和串行运行 Promises 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45766806/