Codiqo

Learn JavaScript · lesson 42 of 60 · about 10 minutes

Promises, async and await

Add a weather widget to Sam's page: represent future values with Promises, and write async code that reads from top to bottom.

What you'll learn

  • Explain what a Promise is
  • Use await inside async functions
  • Handle failures with try...catch

A weather widget

Sam lives in Leeds and wants the page to show the weather there. getWeather(town) doesn't take a callback: it returns a Promise of the weather, which a moment later turns into an object like { temp: 12, sky: "cloudy" }. An async function showWeather() shows Loading the weather..., waits for it with await, and shows Leeds: 12°C, cloudy. For a town it doesn't know, the promise is rejected with an Error, so the waiting goes inside try, and catch shows No weather for now with the reason.

A promise of a value

A Promise is a placeholder for a value that isn't ready yet. It's pending at first, then either fulfilled with a value or rejected with an error.

Inside an async function, await promise pauses that function until the value is ready, without freezing anything else.

A pretend slow lookup

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function getStreak(user) {
  await wait(30);
  return user === "ada" ? 12 : 0;
}

async function main() {
  console.log("Loading...");
  const streak = await getStreak("ada");
  console.log(`Streak: ${streak}`);
}
main();
console.log("(main is running in the background)");

Output

Loading...
(main is running in the background)
Streak: 12

When things go wrong

A rejected promise makes await throw, so you handle it with the try...catch you already know. Promise.all([...]) waits for several promises at once.

Errors and Promise.all

async function load(name) {
  if (name === "bad") throw new Error("Not found");
  return name.toUpperCase();
}

async function main() {
  const both = await Promise.all([load("a"), load("b")]);
  console.log(both.join(" + "));
  try {
    await load("bad");
  } catch (err) {
    console.log("Failed:", err.message);
  }
}
main();

Output

A + B
Failed: Not found

Tip

Sam's page is a module, so it can use await at the top level, outside any function: await showWeather(); waits for the widget before the code below it runs.

Now try it yourself

This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.