2

I've got three promises, like so

const promiseOne = factoryOne.get();
const promiseTwo = factoryTwo.get();
const promiseThree = factoryThree.get();

that need to be returned from a function. Is there any difference between:

return [await promiseOne, await promiseTwo, await promiseThree];

and

await Promise.all([promiseOne, promiseTwo, promiseThree])
return [promiseOne, promiseTwo, promiseThree];

The three promises are kicked off when they're created, so I don't think there will be parallelization issues. Are there any gotchas between these two approaches?

JonLuca
  • 850
  • 6
  • 25
  • I guess the `Promise.all()` one returns synchronously and outside of the the function you can use `await` meanwhile the other does not return until all the 3 `await` for promises has not been finished. – norbitrial Jan 07 '20 at 17:53
  • `Promise.all()` which in itself is a `promise` gets rejected when one (any) of them fails. – ambianBeing Jan 07 '20 at 17:54

1 Answers1

0

There is a difference, but it's not a timing one.

In version one you're returning an array of the results of the promises (or rather, you're returning a Promise that will resolve to that array, since async functions always wrap the return result in an implicit Promise).

In version two you're still returning the promises, not the values to which they've resolved. To return the results instead you'd need to use something like:

let result = await Promise.all([promiseOne, promiseTwo, promiseThree]);
return result;

There are probably also differences in the error handling of the two versions (in the event of any of those three Promises getting rejected) but I'm a little rusty on the interaction there.

Alnitak
  • 334,560
  • 70
  • 407
  • 495