Sub topic 9
Common Mistakes and How to Fix Them
This chapter assumes you can write async functions, use await, handle errors with try/catch/finally, and run several operations together with Promise.all. Each mistake below follows the same pattern: the code looks right, runs without a syntax error, and quietly does the wrong thing. For each one you will see the symptom, the reason, and the fix.
Most of these bugs come from a single fact. Calling an async function gives you a Promise immediately, and nothing waits for that Promise unless your code asks it to. Keep that in mind as you read the examples.
Forgetting await
If you leave out await, the variable holds a Promise object instead of the value you wanted. A Promise is an object, and every object is truthy, so conditions involving it pass every time.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function isAllowed(user) {
await delay(50);
return user === 'admin';
}
async function checkBroken(user) {
if (isAllowed(user)) { // Bug: a Promise is always truthy
console.log(`broken: ${user} granted`);
}
}
async function checkFixed(user) {
if (await isAllowed(user)) {
console.log(`fixed: ${user} granted`);
}
}
checkBroken('guest'); // broken: guest granted
checkFixed('guest'); // prints nothingThe same mistake causes other symptoms:
console.log(result)printsPromise { <pending> }.data.nameisundefined, because a Promise has nonameproperty.JSON.stringify(result)produces{}.- A rejection is never caught by the surrounding
try/catch, because the code never waited for it.
The fix is to add await. TypeScript and the ESLint rules @typescript-eslint/no-floating-promises and @typescript-eslint/no-misused-promises catch this mistake automatically. Turn them on if your project allows it.
Using await Outside an async Function
await only works directly inside an async function or at the top level of an ES module. The mistake people usually make is using it inside a callback. The callback is a separate function, and the fact that the outer function is async does not make the callback async.
async function loadAll(ids) {
// SyntaxError: await is only valid in async functions
// const users = ids.map(id => await fetchUser(id));
// Fix: make the callback async, then wait for all the Promises it returns
const users = await Promise.all(ids.map(async id => fetchUser(id)));
return users;
}
async function fetchUser(id) {
return { id, name: `user${id}` };
}
loadAll([1, 2]).then(console.log); // [ { id: 1, ... }, { id: 2, ... } ]Making the callback async fixes the syntax error. It also changes what the callback returns: it now returns a Promise. The next section covers what happens when the array method ignores that Promise.
Async Callbacks in forEach, filter, and Similar Methods
forEach calls your callback and throws away whatever it returns. An async callback returns a Promise, so forEach starts every operation and returns straight away, before any of them finish.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const ids = [1, 2, 3];
async function broken() {
ids.forEach(async id => {
await delay(100);
console.log('forEach', id);
});
console.log('broken: done'); // prints before any forEach line
}
async function inOrder() {
for (const id of ids) {
await delay(100);
console.log('for...of', id);
}
console.log('inOrder: done'); // prints after all three
}
async function inParallel() {
await Promise.all(ids.map(async id => {
await delay(100);
console.log('map', id);
}));
console.log('inParallel: done'); // prints after all three
}
broken().then(inOrder).then(inParallel);filter causes a nastier version of the same bug. It treats the returned value as a boolean, and a Promise is always truthy, so an async predicate keeps every element.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function isEven(n) {
await delay(10);
return n % 2 === 0;
}
async function main() {
const nums = [1, 2, 3, 4];
const wrong = nums.filter(async n => isEven(n));
console.log(wrong); // [1, 2, 3, 4]
const flags = await Promise.all(nums.map(isEven));
const right = nums.filter((_, i) => flags[i]);
console.log(right); // [2, 4]
}
main();some, every, find, and reduce fail in the same way. Of the built-in array methods, only map is useful with async callbacks, because it keeps the Promises it gets back. You can then pass that array to Promise.all.
Forgetting to Return Inside map
If the map callback has a block body (curly braces), you need an explicit return. Without it, map produces an array of undefined. Promise.all treats non-Promise values as already fulfilled, so it resolves immediately while the real work keeps running with no one waiting on it.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function main() {
const broken = await Promise.all([1, 2].map(id => {
delay(100, id * 10); // missing return
}));
console.log(broken); // [ undefined, undefined ]
const fixed = await Promise.all([1, 2].map(id => {
return delay(100, id * 10);
}));
console.log(fixed); // [ 10, 20 ]
}
main();return Versus return await Inside try
In an async function, return somePromise and return await somePromise normally behave the same. Inside a try block they behave differently. return promise hands the Promise to the caller without waiting for it, so the function has already left the try block by the time the Promise rejects, and the local catch never sees the error.
async function withoutAwait() {
try {
return Promise.reject(new Error('boom'));
} catch {
return 'recovered';
}
}
async function withAwait() {
try {
return await Promise.reject(new Error('boom'));
} catch {
return 'recovered';
}
}
withoutAwait().then(console.log, err => console.log('escaped:', err.message));
withAwait().then(console.log);
// recovered
// escaped: boomThe rule: when you want the surrounding catch or finally to cover a Promise, write return await. Outside try, a plain return is fine.
Floating Promises and Unhandled Rejections
A floating Promise is one that nothing awaits and nothing attaches .catch to. If it rejects, there is no handler. Browsers log an "Uncaught (in promise)" error. Since Node.js 15, an unhandled rejection crashes the process by default.
async function saveLog(message) {
throw new Error(`disk full while saving "${message}"`);
}
async function handleRequest() {
saveLog('request received'); // floating: the rejection goes unhandled
return 'ok';
}
async function handleRequestFixed() {
// Deliberate fire-and-forget: still attach a handler
saveLog('request received').catch(err => console.error('log failed:', err.message));
return 'ok';
}
handleRequestFixed().then(console.log); // ok, then log failed: disk full ...If you start an operation on purpose and don't wait for it, attach .catch right away. Otherwise, await it. A top-level call such as main() in a script also needs a handler, for example main().catch(err => { console.error(err); process.exitCode = 1; }).
A related trap: if you start a Promise early to run things in parallel and await it later, it can reject before you reach the await. Runtimes detect unhandled rejections when the microtask queue empties, so a Promise that rejects while you are awaiting something else gets reported as unhandled even though you planned to await it. Promise.all avoids this because it attaches handlers to every Promise at once.
Wrapping async Code in new Promise
Passing an async function as the Promise executor looks harmless, but it breaks error handling. If the executor throws after an await, the error rejects the executor's own Promise, which nobody watches. The outer Promise never settles.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
function brokenLoad() {
return new Promise(async (resolve) => {
await delay(50);
throw new Error('lost'); // outer Promise stays pending forever
});
}
async function fixedLoad() {
await delay(50);
throw new Error('caught properly');
}
fixedLoad().catch(err => console.log(err.message)); // caught properlyUse new Promise only to wrap callback-based APIs such as setTimeout or older Node.js functions, and keep the executor synchronous. If the code already uses Promises, write an async function.
Accidental Sequential Awaits
Awaiting independent operations one after another adds their durations together. This mistake doesn't cause wrong results, only slow code, so it often goes unnoticed. The previous chapter covered the fix: start the operations first, then await them together.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function main() {
console.time('slow');
const user = await delay(500, 'user');
const posts = await delay(500, 'posts');
console.timeEnd('slow'); // about 1000 ms
console.time('fast');
const [user2, posts2] = await Promise.all([delay(500, 'user'), delay(500, 'posts')]);
console.timeEnd('fast'); // about 500 ms
console.log(user, posts, user2, posts2);
}
main();Keep the operations sequential only when one needs the result of another, or when you have to limit load on a server.
Quick Reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `Promise { <pending> }` in logs, condition always true | Missing `await` | Add `await`; enable lint rules |
| "Done" prints before the work finishes | Async callback in `forEach` | `for...of` or `Promise.all(map)` |
| `filter` keeps every item | Async predicate returns a truthy Promise | Compute flags with `Promise.all`, then filter |
| `Promise.all` returns `undefined` values | Block-body `map` callback without `return` | Add `return` or use a concise arrow |
| Local `catch` never runs | `return promise` inside `try` | `return await promise` |
| Process crashes with unhandled rejection | Floating Promise | `await` it or attach `.catch` |
| Promise never settles | Async executor in `new Promise` | Write a plain async function |
| Code is slow but correct | Independent awaits in sequence | Start together, `await Promise.all` |
Exercise
This function should return only the IDs of active users, but it returns all of them. Explain why and rewrite it. async function activeIds(ids) { return ids.filter(async id => (await getUser(id)).active); }
Show answer
The async predicate returns a Promise, and every Promise is truthy, so filter keeps every ID. Fix: async function activeIds(ids) { const users = await Promise.all(ids.map(getUser)); return ids.filter((_, i) => users[i].active); }
Exercise
A function contains try { return fetchData(); } catch (err) { return fallback; } finally { db.close(); }. When fetchData rejects, the fallback is never returned and the query sometimes fails with "connection closed". Name both problems and the one-word fix.
Show answer
Because the Promise is returned without being awaited, the function leaves the try block right away. The rejection therefore skips the local catch, and finally closes the connection while the query is still running. The fix is to write return await fetchData();.
Exercise
Why does await Promise.all(items.map(item => { process(item); })) finish instantly, and what does it resolve to?
Show answer
The block-body arrow function has no return, so map produces an array of undefined. Promise.all treats those values as already fulfilled and resolves immediately to an array of undefined, while the process calls keep running and nothing waits for them.