正如前面的答案已经说明的那样,Promise.all
将所有已解析的值与与原始 Promises 的输入顺序相对应的数组聚合(请参阅Aggregating Promises)。
但是,我想指出,订单只保留在客户端!
对于开发人员来说,Promise 看起来是按顺序实现的,但实际上,Promise 的处理速度不同。了解何时使用远程后端很重要,因为后端可能会以不同的顺序接收您的 Promise。
这是一个使用超时来演示该问题的示例:
承诺.all
const myPromises = [
new Promise((resolve) => setTimeout(() => {resolve('A (slow)'); console.log('A (slow)')}, 1000)),
new Promise((resolve) => setTimeout(() => {resolve('B (slower)'); console.log('B (slower)')}, 2000)),
new Promise((resolve) => setTimeout(() => {resolve('C (fast)'); console.log('C (fast)')}, 10))
];
Promise.all(myPromises).then(console.log)
In the code shown above, three Promises (A, B, C) are given to Promise.all
. The three Promises execute at different speeds (C being the fastest and B being the slowest). That's why the console.log
statements of the Promises show up in this order:
C (fast)
A (slow)
B (slower)
If the Promises are AJAX calls, then a remote backend will receive these values in this order. But on the client side Promise.all
ensures that the results are ordered according to the original positions of the myPromises
array. That's why the final result is:
['A (slow)', 'B (slower)', 'C (fast)']
If you want to guarantee also the actual execution of your Promises, then you would need a concept like a Promise queue. Here is an example using p-queue (be careful, you need to wrap all Promises in functions):
Sequential Promise Queue
const PQueue = require('p-queue');
const queue = new PQueue({concurrency: 1});
// Thunked Promises:
const myPromises = [
() => new Promise((resolve) => setTimeout(() => {
resolve('A (slow)');
console.log('A (slow)');
}, 1000)),
() => new Promise((resolve) => setTimeout(() => {
resolve('B (slower)');
console.log('B (slower)');
}, 2000)),
() => new Promise((resolve) => setTimeout(() => {
resolve('C (fast)');
console.log('C (fast)');
}, 10))
];
queue.addAll(myPromises).then(console.log);
Result
A (slow)
B (slower)
C (fast)
['A (slow)', 'B (slower)', 'C (fast)']