How To Use Async/Await in JavaScript

Async/Await

The async and await is keywords to perform the promise-based asynchronous operation. In this article, we are going to learn how to use async/await in JavaScript.

How to use Async?

It is mandatory to define the async keyword before any function that turns your normal function to async function. Let’s start to learn it through a very basic example.

Normal Function Example

function sayHello() {
    return 'Hello World!';
}

sayHello(); // Hello World!

Async Function Example

async function sayHello() {
    return 'Hello World!';
}

sayHello(); // [object Promise] { ... }

We could explicitly return a promise with Promise.resolve() like:

async function sayHello() {
    return Promise.resolve('Hello World!');
}
async function sayHello() {
    return 'Hello World!';
}

let greeting = sayHello();
greeting.then((value) => console.log(value)); // Hello World!

or you can try this:

async function sayHello() {
    return 'Hello World!';
}

sayHello().then((value) => console.log(value) ); // Hello World!

We can shorthand the sayHello() async function to:

sayHello().then(console.log); // Hello World!

The async ensure that the function returns a promise.

How to use await?

The await only works inside the async function only. The usage of await is similar to the async, just put it in front of any promise based function to pause until the promise fulfills. Let’s modify our previous example with await.

async function sayHello() {
    let greeting = await Promise.resolve('Hello World!');
    return greeting;
}

or you can use await with fetch api:

async function getTask() {
  let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  if (!response.ok) {
    throw new Error('HTTP error! status: ' + response.status);
  } else {
    return await response.json();
  }
}

getTask().then(console.log);

Error Handling

You can easily handle the errors using the try..catch blocks or simply by using the catch() with the returned promise.

async function getTodos() {
  try{
    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    if (!response.ok) {
      throw new Error('HTTP error! status: ' + response.status);
    } else {
      return await response.json();
    }
  }
  catch(e) {
    console.log(e);
  }
}

or you can use the catch() block on the end of then() block with the returned promise.

async function getTask() {
  let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  if (!response.ok) {
    throw new Error('HTTP error! status: ' + response.status);
  } else {
    return await response.json();
  }
}

getTask()
.then((todo) => {
    console.log(todo)
})
.catch((e) => {
    console.log(e);
});

We hope this article will help to know how to use the async/await. If you like this article then please follow us on Facebook and Twitter.