How to do promise.all for array of array of promises?

Viewed 56341

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]],

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 ?

7 Answers

If you have fixed number of subarrays, I’d suggest to use this simple solution:

const balancePromises = [...];
const symbolPromises = [...];

const [balances, symbols] = await Promise.all([
    Promise.all(balancePromises),
    Promise.all(symbolPromises)
]);

Several promises could also be parallelized like this:

const [
    balances,
    debt,
    name,
] = await Promise.all([
    this.contract.getBalanceOf(user),
    this.contract.getDebtOf(user),
    this.contract.getNameOf(user),
]);

If you are looking to flatten the multi-array, and pend on all promises, you can now do:

const promiseAll = Promise.all(promiseArray.flat());

Here is my snippet.

const a = Promise.resolve(1);
const b = Promise.resolve(2);
const c = Promise.resolve(3);
const d = Promise.resolve(4);

const e = Promise.all([a, b]);
const f = Promise.all([c, d]);

Promise.all([e, f])
    .then(res => console.log(res));

And here is the result.

[[1, 2], [3, 4]]

Related