HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Async / Await

"async and await make promises easier to write". They are built on top of Promises, but they allow you to write asynchronous code that looks and behaves like synchronous code.


The async Keyword

The keyword async before a function makes the function return a Promise, even if it returns a non-promise value.

async function myFunction() {
  return "Hello";
}

// Is equivalent to:
function myFunction() {
  return Promise.resolve("Hello");
}

The await Keyword

The keyword await can only be used inside an async function. It makes JavaScript wait until the promise settles and returns its result.

async function getDisplay() {
  let myPromise = new Promise(function(resolve) {
    setTimeout(function() {resolve("I love JS!!");}, 3000);
  });
  
  document.getElementById("demo").innerHTML = await myPromise;
}

getDisplay();

Error Handling (try...catch)

Instead of using .catch(), you can use the standard JavaScript try...catch block to handle errors in an async function.

async function fetchData() {
  try {
    let response = await fetch('url');
    let data = await response.json();
    console.log(data);
  } catch (err) {
    console.log("Something went wrong:", err);
  }
}
Comparison: Async/await makes complex logic much more readable because it eliminates long .then() chains and keeps everything in a flat, linear structure.

Key Points to Remember

  • async makes a function return a Promise
  • await pauses the execution until the Promise settles
  • await only works inside async functions
  • It makes asynchronous code cleaner and easier to read
  • Use try...catch for professional-grade error management
  • Perfect for parallel operations using Promise.all()
  • Avoid using await in loops if the tasks can run simultaneously