1

I have a few promise functions that I would like to do a promise.all on with async await. However i'm not sure how to do it when there is a 'then' chain in one of them.

For example.

Promise.all([
    promiseFn1(),
    promiseFn2().then(promiseFn3)
])

How would I implement async await when promiseFn2() is chained inside a Promise.all?

I'm thinking of making an annoynmous function but would prefer not to:

await Promise.all([
   promise1.fn(),
   (() =>{ 
       p2response = await promise2Fn(); 
       return promise3Fn(p2response);
   })()
])
Terence Chow
  • 10,755
  • 24
  • 78
  • 141
  • `Promise.all([ promiseFn1(), promiseFn3(await promiseFn2()) ])`? – Patrick Roberts Nov 07 '17 at 09:35
  • Move `promiseFn3()` into `then()` inside `promiseFn2()` – anteAdamovic Nov 07 '17 at 09:37
  • @PatrickRoberts No, [that can lead to unhandled rejections](https://stackoverflow.com/questions/46889290/waiting-for-more-than-one-concurrent-await-operation) – Bergi Nov 07 '17 at 09:44
  • @Bergi it's exactly the same as in the first example, no need to be so pedantic. – Patrick Roberts Nov 07 '17 at 09:45
  • @PatrickRoberts I guess the pedantry is necessary then, as `promiseFn3(await promiseFn2())` does behave differently than `promiseFn2().then(promiseFn3)`. Consider the case where `promiseFn1()` rejects - it's a subtle but important distinction. – Bergi Nov 07 '17 at 09:51
  • That makes sense. So in your answer, it's different because the helper function converts the thrown error into a rejection, allowing `Promise.all()` to prioritize failing on the `promiseFn1()` as intended. – Patrick Roberts Nov 07 '17 at 10:07

1 Answers1

4

Yes, an immediately executed async function expression could do this:

await Promise.all([
    promise1.fn(),
    (async () => promise3Fn(await promise2Fn()) )()
])

However I would recommend to stay with the much simpler .then() call. It's not like anything forces you to use await everywhere…

Alternatively, if you are looking for clean code (and the then chain isn't as simple as in your example but involves function expressions), just use a named helper function:

async function promise2and3fn() {
    return promise3Fn(await promise2Fn());
}
await Promise.all([
    promise1.fn(),
    promise2and3fn()
])

There's no way around these extra functions when you want to use await concurrently, as execution inside a function is always sequential.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375