Promise.all:已解析值的顺序 [英] Promise.all: Order of resolved values

查看:21
本文介绍了Promise.all:已解析值的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 MDN 它看起来像 values 传递给 Promise.all 的 then() 回调包含按照承诺顺序的值.例如:

Looking at MDN it looks like the values passed to the then() callback of Promise.all contains the values in the order of the promises. For example:

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应该按什么顺序排列的规范吗?

Can anybody quote a spec stating in which order values should be in?

PS:运行这样的代码表明这似乎是真的,尽管这当然没有证据 - 这可能是巧合.

PS: Running code like that showed that this seems to be true although that is of course no proof - it could have been coincidence.

推荐答案

不久,保留顺序.

按照您链接的规范,Promise.all(iterable)iterable 作为参数并在内部调用 PerformPromiseAll(iterator, constructor, resultCapability),后者使用 IteratorStep(iterator) 循环遍历 iterable代码>.

Following the spec you linked to, Promise.all(iterable) takes an iterable as a parameter and internally calls PerformPromiseAll(iterator, constructor, resultCapability) with it, where the latter loops over iterable using IteratorStep(iterator).

解析通过Promise.all() Resolve实现 其中每个解析的 promise 都有一个内部 [[Index]] 槽,它标记原始输入中 promise 的索引.

Resolving is implemented via Promise.all() Resolve where each resolved promise has an internal [[Index]] slot, which marks the index of the promise in the original input.

所有这一切意味着输出是严格排序的,因为您传递给 Promise.all() 的迭代是严格排序的(例如,一个数组).

All this means the output is strictly ordered given the iterable you pass to Promise.all() is strictly ordered (for example, an array).

您可以在下面的小提琴 (ES6) 中看到这一点:

You can see this in action in the below 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));
});

这篇关于Promise.all:已解析值的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆