说我有一堆承诺。
const promises = [ /*...*/ ];
Run Code Online (Sandbox Code Playgroud)
当所有的承诺都得到解决时,我希望发生一些事情。以下两种方法有什么区别:
使用 Promise.all
const allDonePromise = Promise.all(promises);
Run Code Online (Sandbox Code Playgroud)串行运行承诺
async function allPromises(promisesArray) {
const results = [];
for (const promise of promisesArray) {
results.push(await promise);
}
return results;
}
const allDonePromises = allPromises(promises);
Run Code Online (Sandbox Code Playgroud)是Promise.all刚好在做什么一个内置allPromises确实还是有别的东西引擎盖下发生,使Promise.all更快。我在哪里可以找到有关内部结构的信息Promise.all?
你可以找到的规格Promise.all中的2015年的ECMAScript语言规范第25.4.4.1。
您自己的实现确实在做正确的事情。区别在于细节:
上面的规范在 25.4.4.1.1.r 点说明了then每个承诺都会被调用。这些调用是同步发生的(注意:不是它们的回调)。每当任何承诺解决时,remainingElementsCount就会递减(参见步骤 2.10)。每当它变为零时,返回的承诺就会被Promise.all解析(注意:同步!)。
现在假设你有一个包含一百万个 promise 的数组,第一个需要最长的解析时间,那么你的函数在函数返回之前仍然需要执行 999999 次等待,而规范中的算法已经处理了那些 999999 的分辨率承诺在第一个解决之前,并且在第一个承诺最终解决之后几乎没有什么可做的。
例如,您可以在这个 polyfill/promise.js 实现中看到这一点(其中计数通过递增发生):
Run Code Online (Sandbox Code Playgroud)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 只是可能的实现之一。
请注意,您的函数不是"Running the promises serially"。承诺正在“运行” *,无论您是否对它们进行了某些操作:只要您构造它们,它们就会完成它们的工作。
唯一被序列化的事情是您开始查看(即等待)相应承诺解决方案的时刻。规范似乎暗示实现应该从一开始就监听所有承诺的回调。这个你可以不实现await在一个循环(嗯,你可以,但你会需要调用async反复功能,每承诺一次,这不会给你任何使用更加任何好处await了then,因为你将需要申请then的async函数返回的承诺)。
然后在this和 参数验证领域还有一些其他(明显的)差异。值得注意的是,ECMA 规范指出:
该
all函数要求其this值是支持构造函数参数约定的Promise构造函数。
* Promise 并没有真正“运行”,因为 Promise 是对象,而不是函数。可能正在运行的是一些在创建承诺对象时启动的异步任务。Promise 构造函数回调可能会调用异步 API(如setTimeout, fetch, ...),这可能会导致resolve. 最好将此中间状态称为“待定”(而不是“正在运行”)的承诺
| 归档时间: |
|
| 查看次数: |
2082 次 |
| 最近记录: |