如何做promise.all的数组承诺? [英] How to do promise.all for array of array of promises?

查看:127
本文介绍了如何做promise.all的数组承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试并行运行函数数组,当每个人都完成时,我想要对该结果进行处理。
我正在使用承诺。现在,我可以将所有函数放在一个数组中,并且可以执行
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]],

每个承诺都是承诺的功能。
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屋!

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