async and await
Async code that reads easily.
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.

- 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.
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));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.
| key | value |
|---|---|
| async function | returns a promise |
| await promise | pause for the value |
| try / catch | handles rejections |
| Only pauses | this 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.
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();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