ES8: async await
7min read
Async await improves how we handle asynchronous code. It is built on top of ES6 Promises (our rescue from callback hell) and aims to give a cleaner and more concise syntax. Similar to ES6 Classes and prototypal inheritance the async await syntax is basically syntactic sugar for Promises.
How it works
The syntax for async await is actually quite intuitive. We use the keyword async to define an asynchronous function. Within the async function we can use the keyword await to literally wait until a Promise is resolved/ rejected (note: fetch also returns a Promise). Another benefit of async await is that we can use try/ catch statements as in synchronous code to do our error handling.
In the following example we will create an async function, fetch the random joke API and await the returned Promise from the API call to be resolved and parsed to json. Then we call the async function getJoke and log the data we receive as soon as getJoke is processed and has a value returned to us. We execute this in a try/ catch statement to do the error handling in case the API call is rejected.
Async await is non blocking
Async await is non blocking code. This is especially important as the Browser has only one single thread for all the tasks (parse HTML, apply CSS, render layout, execute Javascript etc.) and Javascript code is “usually” blocking. Using async code can help to improve the performance and user experience of an app/ website.
In the following example we will create a Promise which will resolve after 2 seconds, clearing our interval “tick”. Then we create an async function asyncCall which calls our Promise resolveAfter2Seconds and awaits its result “resolved” and logs it. The interval tick runs every 100ms and logs “tick” to the console. Immediately after the tick interval is set up, asyncCall is executed. Since setInterval is by default also asynchronous and the way the Javascript event loop works, “calling” from within the asyncCall function gets logged before the first “tick” is logged.
Tick will log exactly 20 times (2000ms) until the Promise is resolved and the interval is cleared. This example shows that async await handles the Promise in the background until it is resolved/ rejected.
Callbacks vs Promises vs async await
Async await gives us arguably a nicer and more concise syntax over Promises and unquestionable over multiple nested callbacks. But judge for yourself comparing callbacks, Promises and async await:
Callback(hell)
ES6 Promises
Async await
I am personally a big fan of async await and thanks to Babel it is easy integratable into our code. For everyone who doesn’t transpile their code: async await is not fully supported yet (and won’t be as long as we need to support IE11. See: https://caniuse.com/#search=async)
Let me know what you think in the comments.
Leave a Reply
Want to join the discussion?Feel free to contribute!