Skip to content
async / await
step 1/7

Reading — step 1 of 7

Learn

~3 min readAsync JavaScript

async/await is syntactic sugar over Promises that makes async code read like synchronous code. The Promise machinery is still running underneath — you've just dropped the .then() chains.

The basic shape

js

Two rules:

  1. async makes a function return a Promise. Even async function f() { return 1; } returns Promise<1>. The body runs synchronously up to the first await.
  2. await pauses the function until the Promise settles, then evaluates to the resolved value (or throws if rejected). It only works inside async functions (or top-level in modules).

Comparison: callback hell → Promise chain → async/await

js

Error handling — try/catch

When you await a rejected Promise, it THROWS. Use try/catch:

js

The try wraps EVERY await inside it. One catch handles failures from any of them.

⚠️ Sequential vs parallel — a common bug

js

If the three calls don't depend on each other, that's wasted time. Run them in PARALLEL:

js

The rule: await only when you NEED the result to proceed. Otherwise kick off the Promise and await later.

⚠️ Don't await inside forEach

js

Use a regular for...of for sequential, or Promise.all(arr.map(...)) for parallel:

js

Top-level await

In ES modules and modern Node, you can await at the TOP level of a module — no async wrapper needed:

js

In a script (non-module), you need an async wrapper: (async () => { ... })();

Common mistakes

  • Forgetting await — calling fetchUser(id) without await returns a Promise (not a User). The next line operates on a Promise object.
  • async forEach — doesn't await. Use for...of or Promise.all(map(...)).
  • Awaiting things sequentially when they could be parallel — slow.
  • Not handling rejections — unhandled rejections crash modern Node.
  • return await (often redundant)return promise is fine; return await promise adds a tiny extra microtask. (One exception: inside try/catch — return await ensures rejections are caught HERE.)

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…