Async JavaScript Part 3: Async/Await


What is Async and Await?

Async and Await are extensions of Promises, If you are not familiar with Promises you can check the last part Async JavaScript Part 2: Promises. Async/Await functions, were added with ES2017 (ES8) allowing us to write synchronous looking code while performing asynchronous operations.

Async functions are executed asynchronously via the event-loop and doesn't block the threat. Async functions are always going to return a value. To make a function asynchronous you need to write the keyword async before function.

Await keyword can be used inside an async function only and is waiting for a Promise to return as a result. await operator blocks only the async function while waiting, not the whole app.

Let's see a simple example

async function myAsyncFunc(){
  let result = await fetch('api/give-me-json');

Here we have async function, inside we are fetching a JSON from and API, and we are telling to wait for the result. But what about error handling, what if there was some kind of error, maybe the server is down or the URL doesn't exist. We can do error handling with adding try and catch block. Let's see in our news example below.

async function myAsyncFunc(){
    let result = await fetch('api/give-me-json');
    return result //If everything was ok we can return the result.
    return error //if something goes wrong, here we can catch the error.

Let's see how they work together with synchronous function in the event-loop.

async function asyncFun(){
  const doWorkPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("hello from async function")
    }, 1000)
  let result = await doWorkPromise;

function secondFun(){
  console.log("hello from sync function")


And the result is:

'hello from sync function'
'hello from async function'

We see how the async function doesn't block the other functions in our app, asyncFun() was called first but executed second. Async and Await extensions were one of the best updates to the JavaScript programming language, now with Async and Await we can write much cleaner and better code.

#javascript #async #es8

Author: Aleksandar Vasilevski |