Linda Ojo

Simple Explanation of Async-Await in Javascript

Published: 2021-02-01
preview-image

To fully appreciate the use of Async-Await you must first understand that by default, JavaScript is synchronous.

Synchronous Functions

In synchronous functions, operations run simultaneously and you can't specify pausing or waiting points.

Example

function solveC() {
    const A = 1;

    const B = 2;

    const C = A + B;

    console.log(C);
}

solveC(); // 3

But if for some reason there is a delay in getting the value 'B', JavaScript will execute other lines of code that aren't delayed.This could result in an error.

In the example below, 'B' is delayed using a promise. Let's check out what the results will be.

function solveC() {
    const getB = () => {
      const executor = (resolve, _reject) => {
        setTimeout(() => resolve(2), 100);
      };
      return new Promise(executor); 
    }
    const A = 1;

    const B = getB();
    
    const C = A + B;

    console.log(C);
}

solveC(); // "1[object Promise]"

JavaScript logs the result before the promise above is fulfilled;

What do we do to get the right result even if B is delayed? How do we ask Javascript to pause and wait for 'B'.

The answer is we make the function asynchronous. This is where async-await comes in.

Note: there are other ways to write asynchronous code. You could use Callback functions and promises.

Asynchronous Functions using Async-Await

To make a function Asynchronous we declare the function using the Async keyword. The word “async” before a function means the function will always returns a promise.

The async function below...

async function One() {
  return 1;
}

is the same as the normal function below that returns a promise.

async function One() {
  return Promise.resolve(1);
}

We can ask JavaScript to wait for a promise to be fulfilled by using the await keyword. It has to be noted that it only makes the async function block wait and not the whole program execution.

The code block below shows how we solve our earlier problem with the use of async-await.

async function solveC() {
    const getB = () => {
      const executor = (resolve, _reject) => {
        setTimeout(() => resolve(2), 100);
      };
      return new Promise(executor); 
    }
    const A = 1;

    const B = await getB(); //waits for promise to be resolved
    
    const C = A + B;

    console.log(C);
}

solveC(); // 3

Note: the await keyword can only be used within async functions.

That's it! Hope this was helpful cause I kept it light for beginners. If you want to read a more advanced explanation of async-await, I recommend this article by Ashay Mandwarya

Subscribe to Newsletter

Be the first to know about quality articles and poems written by Linda Ojo.