Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 156 ยท Asynchronous JavaScript

async and await

Write asynchronous JavaScript that reads like normal code with async functions and await, handle errors with try...catch, and run tasks in parallel.

Promises solved the worst problems of callbacks, but long .then() chains can still be hard to follow. Every step lives in its own little function, values have to be passed along by hand, and error handling sits far away from the code that caused the error.

async and await are syntax built on top of promises. They let you write asynchronous code that reads from top to bottom, like ordinary code: "wait for this, then do that". Nothing about the event loop changes. Your code still never blocks the page; it just looks sequential. In this lesson you will write async functions, handle their errors with try...catch, and learn the most important performance decision in async code: running tasks one after another versus at the same time.

Async functions always return a promise

Put the keyword async in front of any function, and two things change:

  1. The function always returns a promise. If you return 42, callers receive a promise that fulfills with 42.
  2. If the function throws, the promise is rejected with that error instead of the error escaping immediately.
JS What an async function returns

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the order of the output. The last console.log prints first, because promise callbacks always run later, as microtasks, even when the value is already known.

Every function form can be async:

JavaScript
async function load() { /* ... */ }        // declaration
const load = async function () { /* ... */ }; // expression
const load = async () => { /* ... */ };       // arrow function

class Store {
  async load() { /* ... */ }               // method
}

await pauses the function, not the page

Inside an async function, await takes a promise and pauses that function until the promise settles. If the promise fulfills, await gives you its value. If it rejects, await throws the rejection reason, exactly like a throw statement on that line.

While the function is paused, the rest of the program keeps running: other code, timers, clicks, rendering. That's the key difference from a "blocking" wait. Only the async function itself waits.

JS await in action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare it with the same logic as a promise chain:

JavaScript
function brewCoffee() {
  console.log("Grinding beans...");
  return wait(600, "fresh grounds")
    .then((grounds) => {
      console.log("Got", grounds, "- now brewing...");
      return wait(800, "a hot coffee");
    })
    .then((coffee) => {
      console.log("Done:", coffee);
      return coffee;
    });
}

Both versions do exactly the same thing. The await version simply puts each value in a normal const and keeps everything at one level of indentation.

You can await any value. If it isn't a promise, await wraps it in one that is already fulfilled, so await 5 gives 5 (after a microtask tick). That's handy when a function sometimes returns a cached value and sometimes a promise.

Where you can use await

await is only allowed in two places:

  • Inside an async function. Using it in a regular function is a SyntaxError.
  • At the top level of a module. In a JavaScript module (<script type="module">), you can write await outside any function. This is called top-level await. Classic scripts don't allow it.

A common trap is a callback inside an async function. The callback is its own function, so it must be async too:

JavaScript
async function saveAll(items) {
  items.forEach((item) => {
    await save(item); // SyntaxError: the arrow function isn't async
  });
}

Even if you make the arrow async, forEach ignores the promises it returns and won't wait. Use a for...of loop when you want to await each step:

JavaScript
async function saveAll(items) {
  for (const item of items) {
    await save(item); // waits for each save before starting the next
  }
}

The next example uses top-level await. Its TryIt runs as a module, so no wrapper function is needed:

JS Top-level await in a module

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Handling errors with try...catch

Because a rejected promise makes await throw, you handle async errors with the same try...catch you already know. The finally block is perfect for cleanup that must happen either way, such as hiding a loading spinner.

JS try, catch and finally with await

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This TryIt also runs as a module, so it can await showUser(1) at the top level and keep the two runs in order.

Two rules keep error handling sane:

  • Catch where you can do something useful. A low-level function often shouldn't catch at all. Let the error reach the code that can show a message or retry.
  • Never leave a rejection unhandled. If you call an async function without await, .catch() or a surrounding try, a failure becomes an "Uncaught (in promise)" error. Fire-and-forget calls still need .catch().

You can also mix styles. await someTask().catch(() => fallback) handles one specific failure inline without a whole try block.

return await inside try matters. In a try block, return promise hands the promise to the caller before it settles, so your catch never sees its rejection. Write return await promise there if you want the local catch (or finally) to cover it. Outside try, the two forms behave the same.

Sequential vs parallel

This is where async code gets fast or slow. Each await waits for one thing to finish before the next line starts. That's right when step two needs the result of step one. But when the tasks are independent, awaiting them one by one wastes time.

The fix: start all the tasks first, then await them. A promise begins its work the moment it is created; await only waits for the result. Promise.all() waits for an array of promises and gives back an array of results.

JS Sequential vs parallel timing

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sequential version takes about 1.5 seconds; the parallel one takes about 0.5 seconds, the time of the slowest task. With real network requests the difference is often even bigger.

A good habit: when you write several await lines in a row, ask "does this line need the previous result?" If not, group the calls with Promise.all().

Loops: one at a time or all at once

The same choice appears with arrays. for...of with await processes items one by one, which is useful when order matters or when a server limits how many requests you may send. map() plus Promise.all() starts everything at once:

JavaScript
// One at a time, in order
for (const id of ids) {
  const item = await loadItem(id);
  render(item);
}

// All at once, results in the same order as ids
const items = await Promise.all(ids.map((id) => loadItem(id)));

Async functions and the event loop

It helps to know exactly what happens at an await. The async function runs synchronously until its first await. There it hands control back to its caller and lets the rest of the program carry on. When the awaited promise settles, the rest of the function is queued as a microtask and continues from where it stopped.

JS When does an async function pause?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The numbers show the order: the function starts immediately, pauses at await, lets the caller finish, and resumes afterward. That's why code after the call to an async function can run before the code inside it has finished.

Debugging tip: browser DevTools show "async stack traces", so when an error happens after an await you can still see which function called which. Name your async functions instead of using anonymous arrows everywhere, and those traces become much easier to read.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does async function f() { return 5; } return when you call f()?

    An async function always returns a promise. The returned value becomes the promise's fulfillment value.
  2. 2. An awaited promise rejects. What happens on the await line?

    await turns a rejection into a thrown error at that exact line, so ordinary try...catch works.
  3. 3. Three independent requests each take one second. Which code finishes in about one second?

    Promise.all() lets all three requests run at the same time. The other two versions wait for each request before starting the next.
  4. 4. Why doesn't items.forEach(async (item) => { await save(item); }) wait for the saves?

    forEach calls the callback and throws away its return value, so nothing waits. Use for...of with await, or Promise.all() with map().
  5. 5. Where is await allowed outside of an async function?

    Modules support top-level await. Classic scripts and regular functions don't.

Summary

  • async functions always return a promise; returned values fulfill it and thrown errors reject it.
  • await pauses only the current async function until a promise settles, then gives you its value or throws its error.
  • await works inside async functions and at the top level of modules.
  • Handle async errors with try...catch...finally; keep return await inside try blocks.
  • Independent tasks should run in parallel: start them all, then await Promise.all([...]).
  • Use for...of with await for one-at-a-time processing; forEach doesn't wait.

Next: Promise.all, allSettled, race and any โ€” choose the right tool for running many tasks at once.