Coding Techniques
Async/Await · Study material
return vs return await inside try
Returning a promise from inside try hands it to the caller before it settles, so the local catch never sees its rejection. return await keeps the error inside the try block:
const failing = () => Promise.reject(new Error("network error"));
async function withoutAwait() {
try { return failing(); } // the promise is returned before it rejects – catch never runs
catch { return "fallback"; }
}
async function withAwait() {
try { return await failing(); } // await makes the rejection throw inside try
catch { return "fallback"; }
}
console.log(await withoutAwait().catch((e) => `escaped: ${e.message}`));
console.log(await withAwait());
escaped: network error fallback
Async generators and for await…of
An async generator produces values that arrive over time – perfect for paginated APIs and streams. for await…of pulls the next value only when the previous one is processed:
// An async generator yields values that arrive over time; for await…of consumes them
const pages = { 1: ["Asha", "Ravi"], 2: ["Meera"], 3: [] };
const fetchPage = (n) => new Promise((r) => setTimeout(() => r(pages[n]), 5));
async function* allUsers() {
for (let page = 1; ; page++) {
const users = await fetchPage(page);
if (users.length === 0) return; // no more pages
yield* users;
}
}
const names = [];
for await (const name of allUsers()) names.push(name);
console.log(names.join(", "), `(${names.length} users)`);
Asha, Ravi, Meera (3 users)
Patterns at a glance
| Goal | Code |
|---|---|
| Steps that depend on each other | const a = await f(); const b = await g(a); |
| Independent steps | const [a, b] = await Promise.all([f(), g()]); |
| Some may fail | await Promise.allSettled([...]) |
| Process a list in order | for (const x of list) await handle(x); |
| Process a list in parallel | await Promise.all(list.map(handle)) |
| Timeout | await Promise.race([work, timeout]) |
| Stream of values | for await (const v of source) |
Async/await checklist
- await every promise whose result or error you need.
- Wrap awaits in try/catch (or add .catch at the call site).
- Start independent work before awaiting it.
- Use for…of, not forEach, for sequential async loops.
- Use return await inside try when the catch must see rejections.
- Never leave an async function call without handling its rejection.