1

If I have this return statement

return await foo1().then(() => foo2());

and both foo1 and foo2 are async, would the code wait for the resolution of foo2 or only foo1 ?

thanks.

3 Answers3

2

await awaits for the entire expression foo1().then(...), regardless of what ... is. The same applies to a chain of then-s (you asked it in a comment).
Also, you do not really need await here, you could simply return the Promise created by then (or a chain of them), see Difference between `return await promise` and `return promise` for explanation.

tevemadar
  • 12,389
  • 3
  • 21
  • 49
1

return await somePromise(); is an anti-pattern since await wraps the result of somePromise(), which is itself a Promise, in a newly created Promise.

return somePromise(); is the correct form.

Rob Raisch
  • 17,040
  • 4
  • 48
  • 58
0

Yes it will wait because the await operator has lower precedence than the . operator.

However, your code fails to take advantage of await which provides superior readability.

Prefer

await foo1();
const result = await foo2();
return result;
Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84