After this lesson you can write asynchronous code that reads from top to bottom like ordinary code. async and await are a friendlier way to use the promises from the previous lesson. They do not replace promises; they sit on top of them.
The two keywords
Putting async before a function does two things. It lets you use await inside the function, and it makes the function always return a promise.
async function greet() {
return "hi";
}
console.log(greet() instanceof Promise); // trueReturning "hi" gives a promise fulfilled with "hi". Throwing an error inside gives a rejected promise. You can mark function expressions and arrow functions as async too: const load = async () => { ... }.
await goes in front of a promise. The function pauses at that line until the promise settles, then continues with the fulfilled value, or throws the rejection reason if it failed. Crucially, only that function pauses. The rest of the page carries on, just as with .then.
A first example
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const wait = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function main() {
log("start");
const first = await wait(600, "first");
log("got", first);
const second = await wait(600, "second");
log("got", second);
return "finished";
}
main().then(result => log(result));
log("main() has been called");
</script>start
main() has been called
got first
got second
finishedNotice where main() has been called appears. main runs until its first await and then hands control back. The line after the call runs while main waits. After the pauses, the rest continues. Reading main alone, though, you see simple top-to-bottom steps, with no callbacks.
Handling errors
A failed promise makes await throw, so you handle it with the try, catch and finally you already know from Errors, try and catch.
const wait = (ms, value, fail) =>
new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));
async function risky() {
try {
await wait(10, "nope", true);
console.log("unreached");
} catch (error) {
console.log("caught:", error.message);
} finally {
console.log("cleanup");
}
}
risky();
// caught: nope
// cleanupIf you do not catch inside, the error rejects the async function's own promise, so the caller can catch it, either with try around its own await or with .catch(...) on the result. Somewhere up the chain, someone should handle it.
Sequential or parallel?
Each await waits before the next line starts. That is what you want when step two needs step one's answer. When the jobs are independent, awaiting one by one is wasteful.
async function sequential() {
const a = await wait(100, "a"); // about 100 ms
const b = await wait(100, "b"); // another 100 ms
return a + b; // about 200 ms in total
}
async function parallel() {
const [a, b] = await Promise.all([wait(100, "a"), wait(100, "b")]);
return a + b; // about 100 ms in total
}Both return "ab"; with wait as defined above, the first takes roughly 200 milliseconds and the second roughly 100. In parallel, both timers start immediately because the promises are created before anything is awaited. Promise.all then waits for the slower one. When doing network requests, this can make a page noticeably faster.
Loops and arrays
Await works fine inside for and for...of loops, and each iteration waits for the one before:
for (const item of ["x", "y", "z"]) {
console.log(await wait(10, item)); // x, then y, then z, in order
}(That await at the top of a code block needs a module or an async function around it.) For parallel work on an array, map each item to a promise and wait for them all:
const results = await Promise.all(
["x", "y", "z"].map(async item => (await wait(10, item)).toUpperCase())
);
console.log(results); // [ 'X', 'Y', 'Z' ]Be careful with forEach, which is a trap. It does not wait:
[1, 2].forEach(async n => {
await wait(10);
console.log("forEach finished", n);
});
console.log("after forEach");
// after forEach
// forEach finished 1
// forEach finished 2forEach calls your function, ignores the promise it returns and moves on. If you need to wait, use for...of or Promise.all with map.
Where you can use await
Inside any async function. In a module (see Modules: import and export) you can also use await at the top level of the file, with no wrapper function. In an ordinary <script>, you cannot, so wrap the code: async function main() { ... } main();. You can still await a non-promise value, as in await 5, but it only adds a tiny delay.
Mixing styles
Because async functions return promises, they mix freely with .then, .catch and Promise.all. A common pattern is to write the main logic with await and attach one .catch to the outermost call, so nothing fails silently.
Common mistakes
- Forgetting
await. You get a pending promise, not the value. PrintingPromise { <pending> }instead of your data is the telltale sign. - Using
awaitoutside an async function. In a classic script this is a syntax error. Wrap the code in an async function. - Awaiting independent jobs one by one. Start them together and use
Promise.all. - Using
forEachwithawait. It will not wait. Usefor...oformapwithPromise.all. - Swallowing errors. An empty
catchhides failures. Log, show a message or rethrow. - Assuming
asyncmakes code run in parallel or on another thread. It does not. It only lets the function pause and resume, on the same single thread. - Not returning a result. An async function with no
returngives a promise ofundefined.
Exercise
Write async function countdown() that uses a wait(ms) helper to log 3, 2, 1 and "Go!" with a second between each. Then write two versions of a function that waits for three 300 ms promises, one sequential and one with Promise.all, and measure each with Date.now() before and after. The sequential one should take around 900 ms and the parallel one around 300 ms. Last, make one of the promises reject and wrap the call in try/catch.
Next, use these tools on real data from the internet in Fetching data with fetch.
Key points
- An async function always returns a promise, and await pauses that function until a promise settles.
- await only pauses the async function it is in, and the rest of the page keeps running.
- Use try, catch and finally around await to handle rejections like ordinary errors.
- Awaiting jobs one after another is sequential, so start independent jobs together and await Promise.all.
- forEach does not wait for async callbacks, so use for...of for sequential work or map with Promise.all for parallel work.