Sub topic 9
Common Mistakes and How to Fix Them
This chapter assumes you know how async functions return Promises, how await pauses a function, and how try/catch handles rejections. It also assumes you know how Promise.all runs work in parallel. Most async bugs come from a small set of mistakes. Each one below has a symptom you can recognise and a fix.
Forgetting await
Calling an async function without await gives you a Promise, not the value inside it. The code still runs without any error. It just works with the wrong thing.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function getUser() {
return delay(100, { name: 'Ada' });
}
async function main() {
const user = getUser(); // missing await
console.log(user.name); // undefined: user is a Promise
console.log(user instanceof Promise); // true
const fixed = await getUser();
console.log(fixed.name); // Ada
}
main();You will see undefined, [object Promise], or Promise { <pending> } where you expected data. Add await, or chain .then() if you are outside an async function.
Async callbacks inside forEach
forEach calls its callback and throws away whatever the callback returns. When the callback is async, it returns a Promise, and forEach discards that Promise. Nothing waits for it.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const ids = [1, 2, 3];
// Pitfall: forEach does not wait for async callbacks
ids.forEach(async id => {
await delay(100);
console.log('forEach', id);
});
console.log('forEach returned immediately');
// Fix 1: for...of runs the steps one at a time, in order
async function processInOrder() {
for (const id of ids) {
await delay(100);
console.log('for...of', id);
}
}
// Fix 2: map to Promises and await them all in parallel
async function processInParallel() {
await Promise.all(ids.map(async id => {
await delay(100);
console.log('parallel', id);
}));
console.log('all parallel work done');
}
processInOrder().then(processInParallel);Use for...of when order matters or each step depends on the one before it. Use map with Promise.all when the items are independent. The same problem affects filter, some, and reduce when their callbacks are async.
Returning a Promise from try without await
Inside try, return somePromise hands the Promise straight to the caller. If it rejects later, the rejection skips your catch block.
async function risky() {
throw new Error('boom');
}
async function wrong() {
try {
return risky(); // rejection escapes the try block
} catch {
return 'recovered';
}
}
async function right() {
try {
return await risky(); // rejection is thrown here and caught
} catch {
return 'recovered';
}
}
wrong().catch(err => console.log('wrong:', err.message)); // wrong: boom
right().then(value => console.log('right:', value)); // right: recoveredWrite return await whenever the return statement sits inside a try block that is supposed to handle the error.
Fire-and-forget rejections
If you start a Promise and never await it or attach .catch(), a rejection has nowhere to go. Browsers log "Uncaught (in promise)". Since version 15, Node.js ends the process by default when a rejection goes unhandled.
async function save() {
throw new Error('disk full');
}
// Pitfall: save(); // unhandled rejection
// Fix: if you really don't want to wait, still handle the error
save().catch(err => console.error('Save failed:', err.message));Awaiting independent work one by one
Two await lines in a row run one after the other. When the operations don't depend on each other, this adds their durations together for no reason. Start both first and await them together with Promise.all, as the previous chapter showed.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `undefined` or `Promise { <pending> }` instead of data | Missing `await` | Add `await` |
| "Done" logs before the work finishes | Async callback in `forEach` | `for...of` or `Promise.all` with `map` |
| `catch` never runs | `return promise` inside `try` | `return await promise` |
| "Uncaught (in promise)" or Node exits | No handler on a Promise | `await` it or add `.catch()` |
| Slow code that is otherwise correct | Sequential awaits of independent work | `Promise.all` |
Exercise
This function should return the total size of all files, but it always returns 0. Explain why and fix it. async function totalSize(files) { let total = 0; files.forEach(async f => { total += await getSize(f); }); return total; }
Show answer
forEach discards the Promises that the async callback returns, so totalSize returns before any getSize call settles, and total is still 0. Fix it by awaiting all the sizes in parallel: const sizes = await Promise.all(files.map(f => getSize(f))); return sizes.reduce((sum, s) => sum + s, 0); A for...of loop with await inside also works, but it runs the calls one at a time.
Exercise
Why does the catch block in "try { return fetchData(); } catch (e) { ... }" fail to handle a rejection from fetchData, which is an async function?
Show answer
Calling fetchData returns a Promise right away without throwing, so the try block finishes without an error. The rejection happens later, after the function has already returned. Writing "return await fetchData()" makes the rejection throw inside the try block, where catch can handle it.