DevPath · Learn to code ESPTEN

Asynchrony: promises and async/await

async / await and Promise.all

async / await

async/await is syntactic sugar over promises that lets you write asynchronous code that reads as if it were synchronous.

async function loadUser() {
  const response = await fetch("/user"); // waits for the promise
  const data = await response.json();
  return data;
}

To handle errors with await, you use try...catch:

async function load() {
  try {
    const data = await requestData();
    return data;
  } catch (error) {
    console.log("Failed:", error.message);
  }
}

Promise.all: wait for several at once

When you have several independent tasks, don't await them one by one: launch them in parallel with Promise.all, which fulfills when all of them finish.

const [a, b] = await Promise.all([requestA(), requestB()]);

Remember that an async function is identified by fn.constructor.name === "AsyncFunction", and that calling any async function returns an object that is instanceof Promise.

Examples

An async function always returns a promise

async function greet() {
  return "hello";
}
console.log(greet.constructor.name);   // "AsyncFunction"
console.log(greet() instanceof Promise); // true
greet().then((v) => console.log(v));   // "hello"
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← PromisesMicrotasks vs macrotasks →