Home › Learn › JavaScript › Async, errors, and classes

async and await

Lesson 37 of 40. Write asynchronous code that reads top to bottom.

An async function always returns a promise, and inside it await pauses until a promise settles and gives you its value. const user = await getUser(1); reads like ordinary code while the network request happens. Errors from a rejected promise are thrown at the await, so try/catch works.

Awaiting things one after another runs them one after another. When the tasks are independent, start them all and await Promise.all, which runs them at the same time and is usually several times faster. The starter includes a fake getUser(id) that takes a few milliseconds, like a real API call.

async function main() {
  const [a, b] = await Promise.all([getUser(1), getUser(2)]);
  console.log(a.name, b.name);
}
main();

Your task

Using the provided getUser(id), write userName(id) (an async function returning just the name), userNames(ids) returning an array of names, fetching all of them at the same time with Promise.all, and safeUserName(id) returning the name or "unknown" when getUser rejects (it rejects for ids that do not exist).

Hint 1

const user = await getUser(id); return user.name;

Hint 2

const users = await Promise.all(ids.map((id) => getUser(id))); return users.map((u) => u.name); For safeUserName wrap the await in try/catch.

Show the solution
const DB = { 1: { name: "Ada" }, 2: { name: "Alan" }, 3: { name: "Grace" } };
function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => (DB[id] ? resolve(DB[id]) : reject(new Error("no such user"))), 10);
  });
}

async function userName(id) {
  const user = await getUser(id);
  return user.name;
}

async function userNames(ids) {
  const users = await Promise.all(ids.map((id) => getUser(id)));
  return users.map((u) => u.name);
}

async function safeUserName(id) {
  try {
    const user = await getUser(id);
    return user.name;
  } catch (e) {
    return "unknown";
  }
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.