如何为承诺数组的数组做 promise.all? [英] How to do promise.all for array of array of promises?
问题描述
我正在尝试并行运行函数数组,当每个人都完成时,我想处理该结果.我正在使用承诺.现在,我可以将所有函数放在一个数组中并且可以做Promise.all(函数数组)但我有像
I am trying to run array of functions parallel and when everybody finishes I want work on that result. I am using promises. Now, I can put all functions in an array and can do Promise.all(array of functions) But I have array like
[[promise1, promise2], [promise3,promise4], [promise5,promise6]],
其中每个承诺都是promisified函数.Promise 参考文档说 Promise.all 中的参数应该是一个可迭代对象,而我的数组是可迭代的.但它对我不起作用.我认为它正在执行 [promise1, promise2] 作为承诺而不是个人承诺.
where each promise is promisified function. Promise reference document says parameter in Promise.all should be an iterable object and my array is iterable. But it is not working for me. I think It is executing [promise1, promise2] as a promise but not individual promise.
任何人都可以帮助我如何实现它或有更好的方法吗?
Can anybody please help me how I can achieve it or is there any better way ?
推荐答案
你还需要为每个数组项调用Promise.all
:
You need to also call Promise.all
for each array item:
const promise4all = Promise.all(
promiseArray.map(function(innerPromiseArray) {
return Promise.all(innerPromiseArray);
})
);
或直接:
// Fix: Promise.all.bind is required because it seems like Promise.all
// implementation relies on "this"
const promise4All = Promise.all(promiseArray.map(Promise.all.bind(Promise)))
// or
// const promise4All = Promise.all(promiseArray.map(p => Promise.all(p)))
这样外部的 Promise.all
得到了其他 Promise.all
中的分组承诺:
This way the outer Promise.all
gets the grouped promises in other Promise.all
:
promise4all.then(function(promiseGroupResult) {
// promiseGroupResult is the actual result of each promise group
// and you'll be able to get each result this way: promiseGroupResult.somePropertyName
});
这篇关于如何为承诺数组的数组做 promise.all?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!