What is the use of async/await in JavaScript?

Async/await is a language feature in JavaScript that was introduced in ES2017 (also known as ES8). It provides a more intuitive way to write asynchronous code, making it easier to reason about and manage.

Before async/await, asynchronous code was written using callbacks or promises. These techniques can quickly become verbose and difficult to read, especially when multiple asynchronous operations are involved. Async/await simplifies this by allowing developers to write asynchronous code that looks and behaves like synchronous code.

What is async/await?

Async/await is a way to write asynchronous code that looks and behaves like synchronous code. It consists of two keywords: async and await.

async is used to define an asynchronous function. An asynchronous function returns a promise, which resolves with the return value of the function.

Here’s an example:

async function asyncFunc() {
  return "Hello, world!";
}

asyncFunc().then((result) => console.log(result));

In this example, asyncFunc is an asynchronous function that returns the string 'Hello, world!'. We call asyncFunc and then use the then method to log the result of the promise to the console.

await is used to wait for a promise to resolve before continuing execution of the code. It can only be used inside an asynchronous function.

For example:

async function myAsyncFunction() {
  const result = await Promise.resolve("Hello, world!");
  console.log(result);
}

myAsyncFunction();

In this example, myAsyncFunction is an asynchronous function that waits for the promise returned by Promise.resolve to resolve before continuing execution. The result of the promise is assigned to the result variable, which is then logged to the console.

How does async/await work?

When an asynchronous function is called, it returns a promise. The promise is either resolved with the return value of the function, or rejected with an error. The await keyword is used to wait for the promise to resolve before continuing execution of the code.

Here’s an example:

async function myAsyncFunction() {
  const result = await Promise.resolve("Hello, world!");
  console.log(result);
  return "Done!";
}

myAsyncFunction().then((result) => console.log(result));

In this example, myAsyncFunction returns a promise that resolves with the string 'Done!' after the await keyword has finished executing. We call myAsyncFunction and then use the then method to log the result of the promise to the console.

Error handling with async/await

When an error is thrown inside an asynchronous function, the promise returned by the function is rejected with that error. You can use a try/catch block to handle errors.

Here’s an example:

async function myAsyncFunction() {
  try {
    const result = await Promise.reject("Oops!");
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

myAsyncFunction();

In this example, myAsyncFunction awaits a rejected promise, which throws an error. The error is caught by the catch block, which logs the error to the console.

Using async/await with multiple promises

Async/await is especially useful when dealing with multiple promises. Instead of chaining promises together using the then method, you can use await to wait for each promise to resolve before continuing execution of the code.

Here’s an example:

async function myAsyncFunction() {
  const result1 = await Promise.resolve("Hello");
  const result2 = await Promise.resolve("world!");
  console.log(result1 + " " + result2);
}

myAsyncFunction();

In this example, myAsyncFunction awaits two promises, one that resolves with the string 'Hello' and another that resolves with the string 'world!'. The two results are concatenated together and logged to the console.

Converting callback-based functions to async/await

Many older Node.js APIs use callbacks to handle asynchronous operations. These callbacks can become difficult to manage as the codebase grows, so converting them to async/await can make the code more maintainable.

Here’s an example:

function callbackFunction(callback) {
  setTimeout(() => {
    callback("Hello, world!");
  }, 1000);
}

async function myAsyncFunction() {
  const result = await new Promise((resolve) => {
    callbackFunction(resolve);
  });
  console.log(result);
}

myAsyncFunction();

In this example, callbackFunction is a function that takes a callback as an argument and calls it after one second with the string 'Hello, world!'. We define myAsyncFunction as an async function that waits for the promise returned by new Promise to resolve before continuing execution. We pass resolve as the argument to callbackFunction, which resolves the promise with the string 'Hello, world!' after one second. The result of the promise is assigned to the result variable, which is then logged to the console.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: