看着MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all它看起来像values
传递给then()
Promise.all 的回调包含按照 Promise 顺序排列的值。例如:
var somePromises = [1, 2, 3, 4, 5].map(Promise.resolve);
return Promise.all(somePromises).then(function(results) {
console.log(results) // is [1, 2, 3, 4, 5] the guaranteed result?
});
任何人都可以引用说明顺序的规范values
应该在?
PS:运行这样的代码表明这似乎是正确的,尽管这当然没有证据 - 这可能是巧合。
不久,订单被保留 https://www.karltarvas.com/2015/01/21/order-of-resolved-values-in-promise-all.html.
按照您链接到的规范,Promise.all(iterable) https://tc39.es/ecma262/#sec-promise.all需要一个iterable https://tc39.es/ecma262/#sec-iterator-interface作为参数并内部调用PerformPromiseAll(iterator, constructor, resultCapability) https://tc39.es/ecma262/#sec-performpromiseall与它一起,后者循环iterable
using IteratorStep(iterator) https://tc39.es/ecma262/#sec-iteratorstep.
解决是通过实现Promise.all() Resolve https://tc39.es/ecma262/#sec-promise.all-resolve-element-functions每个已解决的承诺都有一个内部[[Index]]
slot,它标记原始输入中promise的索引。
所有这些意味着输出是严格排序的,因为您传递给 Promise.all() 的可迭代对象是严格排序的(例如,数组)。
您可以在下面的小提琴(ES6)中看到它的实际效果:
// Used to display results
const write = msg => {
document.body.appendChild(document.createElement('div')).innerHTML = msg;
};
// Different speed async operations
const slow = new Promise(resolve => {
setTimeout(resolve, 200, 'slow');
});
const instant = 'instant';
const quick = new Promise(resolve => {
setTimeout(resolve, 50, 'quick');
});
// The order is preserved regardless of what resolved first
Promise.all([slow, instant, quick]).then(responses => {
responses.map(response => write(response));
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)