Async and Await
Explore the async-await feature in JavaScript that enhances promise handling by allowing asynchronous code to be written with a synchronous style. Understand the rules of async and await, compare synchronous and asynchronous code structures, and learn when to choose async-await over traditional then-catch methods for clearer and more maintainable 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 theasynckeyword.