Javascript

Async Await in Javascript with examples

We all know that JavaScript is asynchronous by default. But you can make it to synchronous by using methods like callbacks, promises, and Async Await.

In the last two articles, we have talked about Callbacks and Promises in Javascript and discussed how they allow us to write asynchronous code in a synchronous manner. Then why there is a need for another method i.e Async Await in Javascript to do the same Job.

In this article, we are going to learn all about Async Await in Javascript, its benefits and how to use them properly in our daily programming. So without wasting much time, let’s dive in.

Async Await in Javascript

What is Async Await in Javascript?

In very simple words, Async and Await are extensions of promises. If you are not clear with the concepts of Promise and how to use them, you can refer my previous post Promises in JavaScript.

Async/await statements are syntactic sugar that is created on top of JavaScript Promises. They allow us to write Promise-based code as if it were synchronous, but without blocking the main thread.

Here is an example of Async Await in Javascript

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait till the promise resolves (*)

  alert(result); // "done!"
}

f();

How Async Await work in Javascript?

As the name suggests Async Await consists of two words: Async and Await and to understand this concept in detail, we need to understand these two words separately.

Async – Async functions allow us to write promise-based code as if we are writing synchronous code without blocking the execution of the thread. It operates asynchronously via the event-loop.

If you are using Async functions, then it supposed that it will always return a value. Using async simply implies that a promise will be returned, and if a promise is not returned, JavaScript automatically wraps it in a resolved promise with its value. Here is the example for the same.

async function firstAsync() {
  return 27;
}

firstAsync().then(alert); // 27

Await – The await operator is used to wait for a Promise. It must be noted that the await operator can be used only inside an Async function block. The Await operator makes JavaScript wait until the promise returns a result.

It must be noted that it only makes the async function block wait and not the whole program execution.

Here is the example of Async and await used together

async function firstAsync() {
    let promise = new Promise((res, rej) => {
        setTimeout(() => res("Now it's done!"), 1000)
    });

    // wait until the promise returns us a value
    let result = await promise; 
  
    // "Now it's done!"
    alert(result); 
    }
};
firstAsync();

So, that’s all about the Async Await in Javascript. Thanks for reading! and feel free to share and comment down your suggestions.

Leave a Comment