D DevBrainBox

JavaScript Async & Await

JS

What are async & await?

async and await are special keywords in JavaScript that make working with Promises easier and your asynchronous code look more like synchronous code.

They are essentially syntactic sugar over Promises, introduced in ES2017.

async function

If you put async before a function, it always returns a Promise, even if you return a normal value.

async function greet() {
  return "Hello!";
}

greet().then(msg => console.log(msg)); // "Hello!"

Await Function

You can only use await inside an async function.

It pauses the function execution until the Promise is resolved, then returns the resolved value.

function getNumber() {
  return new Promise(resolve => {
    setTimeout(() => resolve(42), 1000);
  });
}

async function showNumber() {
  console.log("Waiting...");
  let num = await getNumber();
  console.log("Got number:", num);
}

showNumber();
Output
Waiting...
(1 second later)
Got number: 42

Example: Fetch API with await

async function getUser() {
  try {
    let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
    let data = await response.json();
    console.log(data.name); // Prints the user's name
  } catch (err) {
    console.log("Error:", err);
  }
}
getUser();
  • await fetch(...) waits for the HTTP response.
  • await response.json() waits for JSON parsing.
  • try...catch handles errors, like if network fails.

Why is async/await better?

  • Avoids callback hell.
  • Avoids chaining .then().
  • Looks like normal step-by-step code.

On this page