Étienne Boutet
Étienne Boutet

Reputation: 23

Awaiting a .then() statement

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.

Upvotes: 1

Views: 322

Answers (3)

Rob Raisch
Rob Raisch

Reputation: 17357

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.

Upvotes: 1

tevemadar
tevemadar

Reputation: 13195

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.

Upvotes: 2

Aluan Haddad
Aluan Haddad

Reputation: 31823

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;

Upvotes: 0

Related Questions