Using async and await to handle asynchronous code
ES2017 introduced a new way to handle asynchronous code, the async
and await
keywords. These keywords are syntactic sugar for promises; they are not a new way to handle asynchronous code, but they make the code much easier to read and write.
Essentially, the async
keyword is employed to define an asynchronous function, while the await
keyword is used to pause and await the resolution of a promise within that function. Even if you use the word async
it doesn’t make you code asynchronously, that will only occur when you actually have asynchronous code on it (a promise). To make it more simple, we can say that in order to use await
, we need to define the code block using async
. Let’s explore more in detail how we can use async
.
async
When a function is defined with the async
keyword, it will always return a promise that can be handled as any regular promise. Let’s see an example:
const asyncFun = async...