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

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

问题描述

查看 MDN ,它看起来像 values 传递给然后() Promise.all的回调包含promises顺序的值。例如:

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?
});

任何人都可以引用规格说明应该在?

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 (即支持 Iterator interface)as as一个参数以及稍后的调用 PerformPromiseAll(iterator, latte的构造函数,resultCapability) r遍历 iterable 使用 IteratorStep(迭代器)

这意味着如果您将可迭代传递给 Promise。 all()是严格订购的,一旦传入,它们仍然会被订购。

Following the spec you linked to, Promise.all(iterable) takes an iterable (that is, an object that supports the Iterator interface) as a parameter and later on calls PerformPromiseAll( iterator, constructor, resultCapability) with it, where the latter loops over iterable using IteratorStep(iterator).
This means that if if the iterable you pass in to Promise.all() is strictly ordered, they will still be ordered once passed in.

解决是通过 Promise.all()Resolve 其中每个已解析的承诺都有一个内部 [[Index]] 的插槽,它标记了原始输入中的承诺索引。

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.

所有这些意味着输出严格按输入进行排序,只要输入是严格排序的(例如,数组)。

All this means that the output is strictly ordered as the input as long as the input 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天全站免登陆