Skip to main content

Command Palette

Search for a command to run...

Async/Await in javaScript

Updated
3 min read
Async/Await in javaScript

async await is one of the most important topic while writing asynchronous code handle network call ( API ) but the question is that callback and promises are also use for writing asynchronous code so.

Why async/await introduced?

async/await introduced in ES2017 help to write asynchronous code.

  • It prevent to callback hell and promises chaining.

  • It is a syntatic sugar of promises.

  • It looks like synchronous code.

  • Return always Promise.

async function main(){
    const name = "Async function";
    return name;
}

console.log(main());
// Output: Promise { 'Async function' }

function main(){
    const name = "Regular function";
    return name;
}

console.log(main());
// Output: "Regular function"

In this example there is one async function and another regular function the async function return promise on the other hand regular function return name.

How async function works?

Let's take a look how the async function works behind the scene async function behaves differently with and without await.

  • Without await keyword async works synchronously.

  • When the await keyword hit so the function behave asynchronously.

    • Execute synchronously until the await keyword hit.

    • It goes to microtask queue.

    • Then the event loop move it to the call stack.

Await keyword concept

It uses when we know the particular task take time like network call, fetch data, reading files.

It pause the flow of execution until the Promise settled , reject or resolve.

When the execution is paused so main thread does not block so engine can execute other scripts.

Error handling with async

Error handling is one of the easiest thing in async programming uses try.. catch.

async function main(){
    try{
        const response = await fetch("https://jsonplaceholder.typicode.com/posts/1")
        const data = await response.json();
        console.log(data);
    }
    catch(err){
        console.log(err);
    }
}

This is the example error handling with async await in the try block that part contain where is changed to get error and if the error occur so it handle by catch block.

Comparison with Promise

As we see now async function return always promise so under the hood async is a promise but it just syntatic sugar of promise let's see.

//---------------Promise------------

const data = new Promise((resolve, reject) => {
  fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then((response) => response.json())
    .then((data) => {
      if (data) {
        resolve(data);
      } else {
        reject('Connection error');
      }
    })
    .catch((err) => reject(err));
});


//----------------Async function------------

async function main(){
    try{
        const response = await fetch("https://jsonplaceholder.typicode.com/posts/1")
        const data = await response.json();
        console.log(data);
    }
    catch(err){
        console.log(err);
    }
}

In this example can see the clear difference the promise code looks giant and when the chaining is get deeply so it become more confusing and hard to debug.

With async await same code become easy to readable and easy to debug so async await just easy way to write promise.