Lesson 13 of 14 · 12 min

Promises and async/await

Some work takes time: downloading data, reading a file, waiting for a timer. JavaScript does not stop and wait. Instead it gives you a promise: an object that will hold the result later.

const later = new Promise(resolve => {
  setTimeout(() => resolve("done!"), 1000);  // after 1 second
});

later.then(value => console.log(value));  // done! (one second later)

async and await

await pauses inside an async function until a promise settles, so asynchronous code reads like normal code:

async function showWeather(getWeather) {
  const weather = await getWeather("Harare");   // waits here
  console.log(`It is ${weather.temp} degrees`);
}

An async function always returns a promise. If an awaited promise rejects (fails), await throws, so you can use try/catch.

Many at once: Promise.all

Awaiting one request after another in a loop is slow. Start them all, then wait for all of them together:

const results = await Promise.all([fetchA(), fetchB(), fetchC()]);

Promise.all resolves to an array of results in the same order as the promises you gave it.

Your task

  1. delay(ms): return a promise that resolves after ms milliseconds.
  2. async getNames(ids, fetchUser): fetchUser(id) returns a promise of { id, name }. Fetch every id at the same time and return the names, in the same order as ids.
  3. async firstName(id, fetchUser): return the user's name, or "unknown" if the request fails.
main.js
function delay(ms) {
}

async function getNames(ids, fetchUser) {
}

async function firstName(id, fetchUser) {
}

// A pretend server for trying things out:
const fetchUser = async id => {
  await delay(200);
  return { id, name: ["Ana", "Tino", "Rudo"][id] ?? "Guest" };
};

console.log(await getNames([0, 1, 2], fetchUser));

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…