The await keyword helps us manage promises in a more procedural manner. The await keyword can be only used inside an async (asynchronous) function to resolve a promise. It helps us resolve promises just like the .then() function we saw earlier. Async... await is the cleanest way to control the flow of a modern asynchronous JavaScript application. An example can be seen here:
async function getPostCategory() {
const postId = 123;
const post = await Post.findById(postId);
return post.category;
}The preceding code block is essentially the same as the one shown here, using the .then() function:
function getPostCategory() {
const postId = 123;
return Post.findById(postId).then(post => {
return post.category;
});
}Note: The await keyword can only be used in async functions.
As seen in the preceding code examples, using async and await, we are able to clearly follow the flow of data in an asynchronous application. Koa takes advantage of this, hence making middleware definition and error handling much easier.