Lesson 17 of 28

In progress

Course progress

JavaScript

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 async and await a promise inside it.
  • Handle failures with try/catch.
  • Run independent work in parallel without blocking.

async makes a promise

JavaScript
Editable. Runs in your browser.





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

JavaScript
Editable. Runs in your browser.





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

JavaScript
Editable. Runs in your browser.





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

JavaScript
Editable. Runs in your browser.





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:

JavaScript
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.

JavaScript
Editable. Runs in your browser.





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

  • forEach with an async callback does not wait. Use for...of or map plus Promise.all.
  • Forgetting to return an awaited value inside then gives the next step undefined.
  • 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 catch produces 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
JavaScript
Editable. Runs in your browser.





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; await pauses only that function.
  • try/catch handles rejections from awaited calls.
  • Use Promise.all for independent work and for...of when 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?
Only in modules. In a classic script, wrap the code in an async function and call it.
Does await block the UI?
No. It suspends the async function and returns control to the event loop, so the page stays responsive.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.