Async and Await
Learn to use async-await to keep the structure identical between synchronous and asynchronous code.
Drawback of using promises
You have seen how promises are superior to callbacks, but there’s one drawback to using promises. The structure of synchronous imperative code is drastically different from the structure of the asynchronous code that uses promises. Unlike the sequential code that flows naturally from one statement or expression to the next, we have to get our head wrapped around the then()
and catch()
sequences.
Solution async-await
The async
and await
feature was introduced to keep the code structure identical between synchronous and asynchronous code. This does not affect the way we write asynchronous functions, but it largely changes the way we use them.
Rules of using async-await
There are two rules for using this feature:
async
: To use an asynchronous function as if it were a synchronous function, optionally mark the promise-returning asynchronous function with theasync
keyword.await
: To call the asynchronous function as if it were a synchronous function, place theawait
keyword right in front of a call. Theawait
keyword may be used only within functions markedasync
.
Synchronous vs asynchronous
Let’s explore this feature by first comparing synchronous to asynchronous code structure. Then, we’ll look at how async
and await
help.
Let’s create two functions—one synchronous and one asynchronous. They both take a number and return the double of the number.
Get hands-on with 1400+ tech skills courses.