Simple Explanation of Async-Await in Javascript

Simple Explanation of Async-Await in Javascript:

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;

    return C;
}

console.log(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. Let’s check out what the results will be.

function solveC() {
    const getB = () => {
        setTimeout(() => {return 2;}, 500); 
    }
    const A = 1;

    const B = getB();

    const C = A + B;

    return C;
}

console.log(solveC()); // NaN

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 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() {
    function getB () {
        setTimeout(() => {return 2;}, 100); 
    }
    const A = 1;

    const B = await getB();

    const C = A + B;
}

solveC();

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

from Tumblr https://generouspiratequeen.tumblr.com/post/641995024687644672

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s