ES6+ Modern JavaScript

Async / Await

async/await is syntactic sugar over Promises that makes asynchronous code look and behave like synchronous code. It dramatically improves readability and simplifies error handling.

How does async/await work in JavaScript?

Mark a function async and you can use await inside it to pause until a promise settles, so asynchronous code reads like normal top-to-bottom code. An async function always returns a promise. Handle errors with try/catch, and use Promise.all to run independent requests in parallel instead of awaiting them one by one.

async function loadProfile(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (err) {
    console.error(err);
    return null;
  }
}

const [user, posts] = await Promise.all([getUser(), getPosts()]);  // parallel

Promise Chain Style

// Promise chaining
fetchUser(1)
.then(user => fetchPosts(user.id))
.then(posts => { return { posts }; })
.catch(err => handleError(err));

async/await Style

// async/await — reads top-to-bottom
async function loadData() {
try {
const user = await fetchUser(1);
const posts = await fetchPosts(user.id);
return { posts };
} catch(err) { handleError(err); }
}

Sequential vs Parallel

The most common async/await mistake is making independent operations run sequentially when they could run in parallel. Always check: do these operations depend on each other?

Slow — Sequential (300ms)
const a = await fetchA(); // wait 100ms
const b = await fetchB(); // wait 100ms
const c = await fetchC(); // wait 100ms
Fast — Parallel (100ms)
const [a, b, c] = await Promise.all([
fetchA(), fetchB(), fetchC()
]);

Common Pitfalls

await inside forEach — doesn't work as expected
Use for…of loop or Promise.all(array.map(async item => ...))
Not handling errors — silent rejections
Always wrap await in try/catch or add .catch() to the returned Promise
Sequential awaits for independent operations (performance)
Use Promise.all() for independent parallel operations
Using await in non-async functions
Mark the function as async first — await is only valid inside async functions

Interactive Examples

Code Editor

<button id="seq">Sequential</button> <button id="par">Parallel</button>
<pre id="out"></pre>

Preview

async/await under the hood

1 / 4
1

async function returns a Promise

Any function marked async always returns a Promise, even if it returns a plain value. return 42 inside async becomes Promise.resolve(42). You can always .then() an async function's return value.

1 of 4
💡Top-level await
In ES modules (.mjs files or type=module), you can use await at the top level without wrapping in an async function. Useful for module initialization: const config = await fetchConfig(). Not available in CommonJS modules.

🎯 Quick Check

What happens if you forget await before a Promise-returning function inside an async function?

Async/Await: summary

Key points

  • await only pauses the current async function; the rest of the page keeps running.
  • Sequential awaits in a row are slow when the requests don't depend on each other.
  • await in a forEach doesn't wait. Use for…of, or Promise.all(items.map(…)).
  • Top-level await works in ES modules.

Frequently asked questions

›Why does my async function return a Promise instead of the value?

Every async function returns a promise. Get the value with await fn() inside another async function, or with fn().then(…).

›Does fetch throw on a 404?

No. fetch only rejects on network failure. Check res.ok (or res.status) and throw yourself.