Reading — step 1 of 7
Learn
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
Two rules:
asyncmakes a function return a Promise. Evenasync function f() { return 1; }returnsPromise<1>. The body runs synchronously up to the first await.awaitpauses the function until the Promise settles, then evaluates to the resolved value (or throws if rejected). It only works insideasyncfunctions (or top-level in modules).
Comparison: callback hell → Promise chain → async/await
Error handling — try/catch
When you await a rejected Promise, it THROWS. Use try/catch:
The try wraps EVERY await inside it. One catch handles failures from any of them.
⚠️ Sequential vs parallel — a common bug
If the three calls don't depend on each other, that's wasted time. Run them in PARALLEL:
The rule: await only when you NEED the result to proceed. Otherwise kick off the Promise and await later.
⚠️ Don't await inside forEach
Use a regular for...of for sequential, or Promise.all(arr.map(...)) for parallel:
Top-level await
In ES modules and modern Node, you can await at the TOP level of a module — no async wrapper needed:
In a script (non-module), you need an async wrapper: (async () => { ... })();
Common mistakes
- Forgetting
await— callingfetchUser(id)without await returns a Promise (not a User). The next line operates on a Promise object. async forEach— doesn't await. Usefor...oforPromise.all(map(...)).- Awaiting things sequentially when they could be parallel — slow.
- Not handling rejections — unhandled rejections crash modern Node.
return await(often redundant) —return promiseis fine;return await promiseadds 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…