Skip to main content

Command Palette

Search for a command to run...

Async/Await in JavaScript

Updated
4 min read
Async/Await in JavaScript

Hey everyone in this blog we are gonna learn about async await in javascript.

What is async await ?

async/await is a modern way to handle asynchronous operations in JavaScript.

It helps us write asynchronous code in a cleaner and more readable way, just like normal synchronous code.

  • async is used before a function to make it return a promise.

  • await is used inside an async function to pause execution until a promise is resolved.

Example:

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data received");
    }, 2000);
  });
}

async function getData() {
  console.log("Start");

  const result = await fetchData();

  console.log(result);
  console.log("End");
}

getData();

Output

Start
Data received
End

Here, await waits for fetchData() to complete before moving to the next line.

Why Was Async/Await Introduced?

Before async/await, JavaScript mainly used callbacks and promises for asynchronous tasks.

But they had problems.

Problem with Callbacks → Callback Hell

getData(function() {
  getMoreData(function() {
    getEvenMoreData(function() {
      console.log("Done");
    });
  });
});

Too much nesting made code hard to read and manage.

This is called callback hell.


Promises Improved It:

getData()
  .then(() => getMoreData())
  .then(() => getEvenMoreData())
  .catch(err => console.log(err));

This is better, but for large projects it can still become difficult to manage.


Async/Await:

Async await was introudced in ES7 to write more managable code for asynchronous operations.

async function runTasks() {
  try {
    await getData();
    await getMoreData();
    await getEvenMoreData();
    console.log("Done");
  } catch (error) {
    console.log(error);
  }
}

This looks like normal step-by-step code and is much easier to understand.

await pauses the execution of the current async function until the promise is resolved.

It does not stop the whole JavaScript program, and it does not block the event loop.

It only pauses that specific async function.

Example:

function delay() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Done");
    }, 2000);
  });
}

async function test() {
  console.log("Start");

  const result = await delay();

  console.log(result);
  console.log("End");
}

console.log("Before function");

test();

console.log("After function");

Output:

Before function
Start
After function
Done
End

Error Handling with Async Code

When working with asynchronous code, errors can happen during API calls, file handling, database operations, or timers.

JavaScript provides different ways to handle these errors depending on whether we use promises or async/await.


Error Handling with Promises

In promises, we use .catch() to handle errors.

Example

function fetchData() {
  return new Promise((resolve, reject) => {
    let success = false;

    if (success) {
      resolve("Data fetched successfully");
    } else {
      reject("Something went wrong");
    }
  });
}

fetchData()
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

Explanation

If the promise is resolved, .then() runs.

If the promise is rejected, .catch() handles the error.


Error Handling with Async/Await

In async/await, we use try...catch.

Example

function fetchData() {
  return new Promise((resolve, reject) => {
    let success = false;

    if (success) {
      resolve("Data fetched successfully");
    } else {
      reject("Something went wrong");
    }
  });
}

async function getData() {
  try {
    const result = await fetchData();
    console.log(result);
  } catch (error) {
    console.log(error);
  }
}

getData();

Explanation

The try block runs the async code.

If an error happens, control moves to the catch block.

This makes error handling cleaner and easier to read.

Comparison: Promises vs Async/Await

Promises Async/Await
Uses .then() and .catch() Uses try...catch
Can become harder to read in long chains Looks like normal synchronous code
Good for simple chaining Better for complex logic
Error handling is done using .catch() Error handling is done using try...catch
Slightly more verbose in complex cases Cleaner and easier to maintain

Conclusion

Async/await is a modern and cleaner way to handle asynchronous code in JavaScript. It helps developers write code that looks simple and readable, just like synchronous code, while still working with asynchronous operations like API calls, file handling, database queries, and timers.

Before async/await, JavaScript mainly used callbacks and promises. Callbacks often led to callback hell, and promises improved the structure but could still become difficult to manage in complex applications.

With async/await, we can write step-by-step code using await, making it easier to understand, debug, and maintain. Error handling also becomes simpler with try...catch, which feels more natural compared to .catch() in promises.

In short, async/await makes asynchronous programming more efficient, readable, and developer-friendly, which is why it is widely used in modern JavaScript applications.