AI Hints
JavaScript · Lesson 84 of 138

async and await

Async code that reads easily.

⏱ 2 min read▶ Video at 1:41:19🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Async and await are built on promises, but they let you write async code that looks like normal step by step code. They're how most modern JavaScript is written.

async and await
From the video: async and await
  • Built on promises
  • Looks like normal code
  • The modern way

await

Putting async in front of a function lets us use await inside it. Await pauses this function until the promise settles, and gives us its value. So the steps read top to bottom. And normal try and catch handles errors. Run it.

app.jsjavascript
const wait = (ms, value) =>
  new Promise(resolve => setTimeout(() => resolve(value), ms));

async function makeBreakfast() {
  try {
    const toast = await wait(100, "toast");
    console.log("Made", toast);
    const tea = await wait(100, "tea");
    console.log("Made", tea);
    return `${toast} and ${tea}`;
  } catch (err) {
    console.log("Breakfast failed:", err.message);
  }
}

makeBreakfast().then(meal => console.log("Breakfast is", meal));
Output
Made toast
Made tea
Breakfast is toast and tea

Rules of await

Await only works inside an async function, or at the top level of a module. An async function always returns a promise, even if you return a plain value. And await only pauses that one function. The rest of your program keeps running.

keyvalue
async functionreturns a promise
await promisepause for the value
try / catchhandles rejections
Only pausesthis function

Awaiting in a loop

You can use await inside a normal for loop, so each step waits for the one before. This is perfect when the order matters, like steps in a recipe. If the steps don't depend on each other, start them together instead, which we'll see next. Run it.

app.jsjavascript
const wait = (ms, value) =>
  new Promise(resolve => setTimeout(() => resolve(value), ms));

async function recipe() {
  for (const step of ["chop", "fry", "serve"]) {
    const done = await wait(100, step);
    console.log("Finished:", done);
  }
  console.log("Dinner is ready");
}

recipe();
Output
Finished: chop
Finished: fry
Finished: serve
Dinner is ready

Summary

Async functions can await promises, so async code reads top to bottom, and try and catch handle errors. Next, running promises at the same time.

Key takeaways
  • async function
  • await
  • try / catch
Next up: Promise.all — many at once