看MDN看起来传递给 Promise.all 的 then()
回调的 values
包含按 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:运行这样的代码表明这似乎是真的,尽管这当然不能证明——这可能是巧合。
最佳答案
按照您链接到的规范,Promise.all(iterable)
需要 iterable
作为参数并在内部调用 PerformPromiseAll(iterator, constructor, resultCapability)
使用它,后者使用 IteratorStep(iterator)
循环 iterable
.
解析通过Promise.all() Resolve
实现其中每个已解析的 Promise 都有一个内部 [[Index]]
槽,用于标记原始输入中 Promise 的索引。
这意味着输出是严格排序的,因为您传递给 Promise.all() 的迭代是严格排序的(例如,一个数组)。
您可以在下面的 fiddle (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));
});
关于javascript - Promise.all : Order of resolved values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28066429/