Promises and async/await relationship
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.
async function returns Promise
The first nugget of knowledge is that the invocation of an
async function returns a Promise.
await result of Promise
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
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
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.
.catch() is the equivalent of a
Node doesn't wait for your database call to finish?
Learn how asynchronous calls work and make your app run as you intended. Get short email course on asynchronicity and two chapters from Finish Your Node App.