Lesson 17 of 28
In progress
async and await
Write asynchronous code that reads top to bottom, handle failures with try/catch, and avoid the await-in-a-loop slowdown.
async and await are syntax over promises. They do not replace promises; they make the common case read like ordinary sequential code, which is much easier to review.
What you will learn
- Mark a function
asyncand await a promise inside it. - Handle failures with
try/catch. - Run independent work in parallel without blocking.
async makes a promise
Editable. Runs in your browser.
console.log(load());
load().then((value) => console.log(value));
Press Run to see the output.
Calling an async function always returns a promise. Returning a plain value resolves it; throwing rejects it. That is why callers use then or await even when the body looks synchronous.
await pauses one function
Editable. Runs in your browser.
async function run() {
console.log("before");
const value = await wait(50, "result");
console.log("after", value);
}
run();
console.log("this runs first");
Press Run to see the output.
await suspends run until the promise settles. It does not block the page: the last line runs while run is waiting. That is the key mental model — only the async function pauses.
Errors with try/catch
Editable. Runs in your browser.
loadTodo(1).then((todo) => console.log(todo?.title));
loadTodo(999999).then((todo) => console.log(todo));
Press Run to see the output.
A rejection inside an awaited call throws at the await, so a normal try/catch works. The alternative is .catch() on the returned promise, which is fine at a call site that only needs to log.
Do not swallow errors silently. Returning null is a decision; it should be documented and the caller should handle it.
Parallel work
Editable. Runs in your browser.
timed();
Press Run to see the output.
Two awaits in sequence wait for each other. Promise.all starts both immediately and waits for both, which is what you want for independent requests. Starting a request and awaiting it later also works:
Editable. Runs in your browser.
Press Run to see the output.
Both requests begin before either is awaited, because calling fetch starts the work immediately.
Top-level await and modules
In a module (type="module"), await can appear at the top level. That is convenient for setup code, and it delays the module’s evaluation, so keep it away from anything that must run immediately.
<script type="module">
const response = await fetch("/data.json");
console.log(await response.json());
</script>
Classic scripts do not allow top-level await; wrap the code in an async function instead.
Async inside event handlers
Event handlers can be async, and the browser ignores the returned promise, so an unhandled rejection will not be caught by anything. Wrap the body in try/catch and report failure in the interface.
Editable. Runs in your browser.
button.addEventListener("click", async () => {
button.disabled = true;
try {
await new Promise((resolve) => setTimeout(resolve, 120));
button.textContent = "Loaded";
} catch (error) {
button.textContent = "Try again";
} finally {
button.disabled = false;
}
});
Press Run to see the output.
This is also where double submissions happen: a second click starts a second request while the first is running. Disabling the control for the duration, as above, is the simplest prevention.
A live search needs the opposite problem solved: earlier responses can arrive after later ones and overwrite good results. Keep a request counter and ignore a response whose number is not the latest, or cancel the previous request with an AbortController.
Common mistakes
forEachwith an async callback does not wait. Usefor...oformapplusPromise.all.- Forgetting to return an awaited value inside
thengives the next stepundefined. - Awaiting inside a loop serialises work that could be parallel; decide which behaviour you need. Sequential awaits are correct when each request depends on the previous response, such as following a pagination cursor. That is also why a retry loop should await each attempt, instead of firing every retry at once and hammering the server.
- A missing
catchproduces an unhandled rejection that may only appear in the console.
for (const url of urls) { await load(url); } is correct when order matters and slow when it does not. Conversely, urls.forEach(async (url) => { await load(url); }) looks parallel and actually does not wait at all, so any code after it runs too early. Choose for...of for sequence or Promise.all(urls.map(load)) for parallel, and never forEach with async.
Write loadAll(ids) that fetches several todos in parallel, filters out failed ones, and returns the titles. Show the count of successes and failures.
Show solution
Editable. Runs in your browser.
const titles = results
.filter((result) => result.status === "fulfilled")
.map((result) => result.value.title);
return { titles, failed: results.length – titles.length };
}
loadAll([1, 2, 999999]).then(({ titles, failed }) => {
console.log(titles.length, failed);
});
Press Run to see the output.
allSettled keeps one bad id from discarding the good results. The count of failures comes from the same array, so the report cannot disagree with itself.
Recap
- An async function always returns a promise;
awaitpauses only that function. try/catchhandles rejections from awaited calls.- Use
Promise.allfor independent work andfor...ofwhen sequence matters.
Next, you will keep small amounts of data in the browser so a page remembers between visits.
Can I use await at the top level of a script?
Does await block the UI?
Progress is saved in this browser only. No account, no email.