Promises and async/await relationship

NAVIGATION

Invocation of async function returns Promise

You can await result of Promise

await equivalent of .then()

You might have been using async/await fluently in your programs. But once in a while, you still see glimpses of Promises. For example, when waiting for multiple asynchronous calls to finish with Promise.all(). You might be wondering what's the relationship between Promises and async/await.

You can revisit the relationship between callbacks and Promises in this article.

Invocation of async function returns Promise

The first nugget of knowledge is that the invocation of an async function returns a Promise.

Code 1

You can await result of Promise

You can await a Promise. Your piece of code returns control back to the system. In the meantime, other parts of your program can execute. When the Promise you awaited upon settles, the runtime will continue executing your code. In case the Promise rejects, execution continues from the nearest catch-block or .catch()-handler.

Code 2

The restriction is that you have to be inside an async function. You're also allowed to do this on the top level when TC39 proposal top-level-await lands in Node.

await equivalent of .then()

Promises and async/await are interchangeable. Whenever you see an await-statement, you can replace it with a .then(). This is a good exercise to play in your mind when reasoning about code containing both constructs. But, when talking about program-wide conventions, it's advisable to stick to one consistently.

Code 3

Similarly, .catch() is the equivalent of a catch-block.

Related articles

Semantic Versioning Cheatsheet

Semantic Versioning Cheatsheet

Learn the difference between caret (^) and tilde (~) in package.json.

Get Cheatsheet

Loading Comments