Home > Software design >  Using Promise.all but only want the value of 2 of the resolved promises?
Using Promise.all but only want the value of 2 of the resolved promises?

Time:07-15

I understand that I can do this to make things cleaner:

const [result2, result3] = await Promise.all([p2, p3]);

but i have the following code where I only care about the values of 2 of the promises. Is there I way I can adapt this following code to be cleaner like the above?

// array of other Promises
this.allAwaitingPromises = [p1, p4];

await Promise.all(this.allAwaitingPromises);
const result2 = await p2();
const result3 = await p3(); 

CodePudding user response:

List the two values you want first in the array of promises, then list the others later. You can then use Promise.all on the whole array, but destructure to only use the first two values from it.

const [result2, result3] = await Promise.all([p2, p3, p1, p4]);

or, if p2 and p3 are functions that return promises, but p1 and p4 are just promises -

const [result2, result3] = await Promise.all([p2(), p3(), p1, p4]);
  • Related