Asynchronous JavaScript
Node.js async await
async marks a function as returning a promise; await pauses inside it until a promise settles. Together they let asynchronous code be written and read as if it were sequential, with ordinary try/catch for errors.
What is async await in Node.js?
async marks a function as returning a promise; await pauses inside it until a promise settles. Together they let asynchronous code be written and read as if it were sequential, with ordinary try/catch for errors.
async await example
// SLOW — 300ms total, each waits for the previous
const user = await getUser(id); // 100ms
const jobs = await getJobs(id); // 100ms
const apps = await getApplications(id); // 100ms
// FAST — 100ms total, all three start immediately
const [user, jobs, apps] = await Promise.all([
getUser(id),
getJobs(id),
getApplications(id),
]);How this works
The first version is sequential because each await blocks the next line. When the calls do not depend on each other, starting them together and awaiting once is three times faster.
Error handling
async function loadJob(id) {
try {
const res = await fetch(`https://api.example.com/jobs/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
logger.error({ err, id }, 'failed to load job');
throw err; // rethrow so the caller can decide
}
}Key points to remember
- An async function always returns a promise, even when it returns a plain value.
- await only works inside an async function, or at the top level of an ES module.
- return await inside try is needed to catch a rejection locally.
Common mistakes with async await
- Awaiting inside a for loop when the iterations are independent.
- Forgetting await, so you operate on a Promise object instead of the value.
- An async function passed to forEach — forEach ignores the returned promise.
Node.js async await— Interview Questions & FAQs
Why does my for loop with await run so slowly?+
Each iteration waits for the previous one to finish. If the iterations are independent, map them to promises and await Promise.all instead — or use a concurrency-limited pool for large sets.
Why does forEach not wait for my async callback?+
forEach ignores return values, so the promises are never awaited. Use a for...of loop for sequential work, or Promise.all(array.map(fn)) for concurrent work.
