Nested promise.all

502 Views Asked by At

I am try to improve some performance problem and for this I am try to do followings

I have a promises array and I wanna return result of this after all promises at promises array are done.

by the way result of processA, processB and processC are important too because at // other logic I use them at somewhere.

const promiseResults = await Promise.all(promises);

 const [processA, processB, processC] = await Promise.all([
      asyncProcessForA(),
      asyncProcessForB(),
      asyncProcessForC(),
 ]);



 // other logic 
 // ....
 // ....


 return promiseResults;

So, I wanna add promiseResults inside promise.all like

const [promiseResults, processA, processB, processC] = await Promise.all([
      Promise.all(promises),
      asyncProcessForA(),
      asyncProcessForB(),
      asyncProcessForC(),
 ]);


 // other logic 
 // ....
 // ....


 return promiseResults;

So, Is my way is good or not and also using nested promise.all is a good way or not? Because I do some search for best practices for using nested promise.all but I could not find anything So, what do you offer ?

2

There are 2 best solutions below

1
On

I haven’t use such construction, but if you don’t like it, you can wrap your promise.all in another promise, so it won’t be nested promise all.

0
On

Using a nested Promise.all() as shown in your second example:

const [promiseResults, processA, processB, processC] = await Promise.all([
      Promise.all(promises),
      asyncProcessForA(),
      asyncProcessForB(),
      asyncProcessForC(),
]);

Works just fine. Promise.all() expects an array of promises. Since Promise.all() returns a promise, it's perfectly fine to use its promise in another call to Promise.all(). The one gotcha here is that your outer Promise.all() will resolve to an array that has an embedded array in it like this:

[[v1, v2, v3], valueA, valueB, valueC]

Where [v1, v2, v3] are the resolved results from the inner Promise.all() (as passed through to the outer Promise.all()andvalueA, valueB, valueCare the resolved results from the other promises passed to the outerPromise.all()`. So, as long as you're prepared for the results to be organized like this, you can certainly work it this way.


You could also flatten the results and do something like this:

const [processA, processB, processC, ...promiseResults] = await Promise.all([
      asyncProcessForA(),
      asyncProcessForB(),
      asyncProcessForC(),
      ...promiseResults
]);

This would then give you a single combined and flat array of results which you can then assign out of or access however you want. So, it really just depends upon how you want the results organized.