Next →

Async/Await in JavaScript

Async/Await is a modern syntax for working with asynchronous code that makes it easier to read and write.

Using Async Functions

Mark a function with async to enable the use of await inside it. await pauses the execution until a Promise resolves.

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function asyncExample() {
  console.log("Start");
  await delay(1000);
  console.log("One second later");
}

asyncExample();

This code logs "Start", waits 1 second, then logs "One second later".

Error Handling

Use try/catch blocks inside async functions to handle errors.

async function fetchData() {
  try {
    let response = await fetch("https://api.example.com/data");
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error:", error);
  }
}