HomeJAVASCRIPTExplain async/await in JavaScript.

Explain async/await in JavaScript.

🔹 1. What is async/await?

  • async/await is syntactic sugar over Promises in JavaScript.
  • It makes asynchronous code look and behave more like synchronous code, which makes it easier to read, write, and debug.

🔹 2. The async keyword

  • Declaring a function with async means the function always returns a Promise.
  • Inside an async function, you can use await.
async function greet() {
  return "Hello!";
}

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

Even though return "Hello!" is not explicitly wrapped in a Promise, JavaScript automatically wraps it.


🔹 3. The await keyword

  • await can only be used inside an async function.
  • It pauses execution of the async function until the Promise is resolved or rejected.
  • It makes asynchronous code behave like synchronous code.
function getData() {
  return new Promise(resolve => {
    setTimeout(() => resolve("Data received"), 2000);
  });
}

async function fetchData() {
  console.log("Fetching...");
  let result = await getData();  // waits until promise resolves
  console.log(result);
}

fetchData();
// Output:
// Fetching...
// (after 2 seconds) Data received

🔹 4. Error handling with try...catch

Instead of using .catch() like with Promises, you can use try...catch.

function getDataWithError() {
  return new Promise((_, reject) => {
    setTimeout(() => reject("Something went wrong"), 2000);
  });
}

async function fetchData() {
  try {
    let result = await getDataWithError();
    console.log(result);
  } catch (error) {
    console.error("Error:", error);
  }
}

fetchData();
// Output: Error: Something went wrong

🔹 5. Running multiple Promises in parallel

If you use await one by one, it runs sequentially. For parallel execution, use Promise.all().

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

async function runTasks() {
  // Sequential
  let a = await task(1000);
  let b = await task(2000);
  console.log("Sequential:", a, b);

  // Parallel
  let [x, y] = await Promise.all([task(1000), task(2000)]);
  console.log("Parallel:", x, y);
}

runTasks();

✅ Summary:

  • async makes a function return a Promise.
  • await waits for a Promise to resolve/reject.
  • Makes async code look synchronous.
  • Use try...catch for error handling.
  • Use Promise.all() for running tasks in parallel.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *