Sub topic 14
Common Mistakes: Forgotten Returns, Sequential Awaits and More
This chapter assumes you already know how chaining, catch, the combinators (Promise.all and the rest) and async/await work. It covers the mistakes that show up most often in real promise code. Each one runs without a syntax error, so it is easy to miss. For each mistake you will see the symptom, the cause, and the fix.
All examples use this helper and two fake data loaders. Paste them first if you want to run the snippets in Node.js or a browser console.
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
function loadUser(id) {
return delay(50, { id, name: 'Ada' });
}
function loadPosts(user) {
return delay(50, [`post by ${user.name}`]);
}Forgotten Returns in then Handlers
The symptom
The next step in the chain gets undefined, or it runs before the work it should wait for has finished.
loadUser(1)
.then((user) => {
loadPosts(user); // promise created, then thrown away
})
.then((posts) => console.log('bug:', posts)); // bug: undefinedWhy it happens
A then handler's return value decides what the next promise settles with. A block body { ... } with no return returns undefined. The chain does not know about the promise from loadPosts, so it moves on right away. If that promise rejects later, nothing is listening to it, and you get an unhandled rejection.
The fix
Return the promise. An arrow function with an expression body does this for you.
loadUser(1)
.then((user) => loadPosts(user))
.then((posts) => console.log('fixed:', posts)); // fixed: [ 'post by Ada' ]Nesting Instead of Chaining
Nesting is related to the forgotten return. People coming from callbacks often write this:
loadUser(1).then((user) => {
loadPosts(user).then((posts) => {
console.log(user.name, posts.length);
});
});It works, but the inner promise is detached. A .catch added to the outer chain will not see errors from loadPosts. Flatten the chain by returning. If a later step needs an earlier value, carry it along in an object, or switch to async/await, where each value stays in scope:
async function showSummary() {
const user = await loadUser(1);
const posts = await loadPosts(user);
console.log(user.name, posts.length); // Ada 1
}
showSummary().catch(console.error);return Versus return await Inside try
In an async function, try/catch only catches a rejection that happens while the function is waiting at an await inside the try block. If you return a promise without awaiting it, the function exits the try block first, so the catch never runs.
const failLater = () =>
new Promise((_, reject) => setTimeout(() => reject(new Error('late')), 10));
async function withoutAwait() {
try {
return failLater(); // the rejection happens after we leave try
} catch (err) {
return 'handled';
}
}
async function withAwait() {
try {
return await failLater(); // the rejection is thrown here, inside try
} catch (err) {
return 'handled';
}
}
withoutAwait().then(console.log, (err) => console.log('escaped:', err.message)); // escaped: late
withAwait().then(console.log); // handledOutside a try block, return promise and return await promise behave the same for the caller. Inside one, use return await.
Missing await and Floating Promises
A floating promise is one that nobody awaits, returns, or attaches a catch to. The most common cause is calling an async function and forgetting await:
async function save(record) {
await delay(20);
if (!record.name) throw new Error('name required');
return 'saved';
}
async function handler() {
try {
save({}); // missing await: the error escapes the try block
console.log('done'); // logs immediately, before save finishes
} catch (err) {
console.log('never reached');
}
}
handler();handler reports success, and the rejection from save turns into an unhandled rejection. In Node.js 15 and later, an unhandled rejection crashes the process by default. Add await. If you really do want fire-and-forget, attach a handler explicitly: save(data).catch(logError).
Accidental Sequential Awaits
Each await pauses the function until its promise settles. If two operations don't depend on each other, awaiting them one after the other adds their times together.
async function slow() {
console.time('slow');
const user = await loadUser(1); // 50 ms
const settings = await delay(50, { theme: 'dark' }); // another 50 ms
console.timeEnd('slow'); // about 100 ms
return { user, settings };
}
async function fast() {
console.time('fast');
const [user, settings] = await Promise.all([
loadUser(1),
delay(50, { theme: 'dark' }),
]);
console.timeEnd('fast'); // about 50 ms
return { user, settings };
}
slow().then(fast);Sequential code is correct when one step needs the previous step's result, as loadPosts needs user. It is also correct when you have to limit load on a server. Choose on purpose:
A subtler form of this mistake creates the promises up front but then awaits them in sequence. That version does run concurrently, because a promise's work starts when the promise is created. But if the first one hangs, you won't see the second one's rejection until later, and if the second rejects while the first is still pending, Node may report it as unhandled. Promise.all attaches handlers to every promise at once, so prefer it.
async Callbacks Inside forEach
Array.prototype.forEach ignores the return value of its callback. When the callback is async, each call returns a promise that nobody waits for.
const ids = [3, 1, 2];
async function brokenSum() {
let total = 0;
ids.forEach(async (id) => {
const n = await delay(id * 10, id);
total += n;
});
return total; // returns before any callback finishes
}
async function sequentialSum() {
let total = 0;
for (const id of ids) {
total += await delay(id * 10, id); // one at a time
}
return total;
}
async function concurrentSum() {
const values = await Promise.all(ids.map((id) => delay(id * 10, id)));
return values.reduce((a, b) => a + b, 0);
}
brokenSum().then((t) => console.log('broken:', t)); // broken: 0
sequentialSum().then((t) => console.log('sequential:', t)); // sequential: 6
concurrentSum().then((t) => console.log('concurrent:', t)); // concurrent: 6map, filter and reduce have the same problem. map at least gives you an array of promises you can pass to Promise.all. filter treats every promise as truthy and keeps every element.
The Explicit Construction Antipattern
Wrapping a promise you already have in new Promise adds code and usually loses errors:
// Antipattern: if loadUser rejects, reject is never called
function getNameBad(id) {
return new Promise((resolve, reject) => {
loadUser(id).then((user) => resolve(user.name));
});
}
// Better: chain on the existing promise
function getName(id) {
return loadUser(id).then((user) => user.name);
}
getName(1).then(console.log); // AdaUse the Promise constructor only to wrap something that isn't a promise yet, such as a timer, an event, or an error-first callback API.
then(onFulfilled, onRejected) Versus catch
The second argument to then only handles a rejection from the promise before that then. It does not see errors thrown by the first argument.
Promise.resolve(1)
.then(
() => { throw new Error('in success handler'); },
() => console.log('not called')
)
.catch((err) => console.log('caught later:', err.message)); // caught later: in success handlerThe two-argument form is useful when you want to handle only the earlier failure. For a general safety net, put a .catch at the end of the chain.
Forgetting That Promises Are Eager
A promise does not store work to run later. Its work is already running when you get the promise. To retry an operation, run it lazily, or cap how many run at once, pass functions that create promises:
async function retry(makeAttempt, times) {
for (let i = 0; i < times; i++) {
try {
return await makeAttempt(); // a fresh promise each attempt
} catch (err) {
if (i === times - 1) throw err;
}
}
}
let calls = 0;
retry(() => {
calls++;
return calls < 3 ? Promise.reject(new Error('flaky')) : Promise.resolve('ok');
}, 5).then((v) => console.log(v, 'after', calls, 'calls')); // ok after 3 callsIf you passed a single promise to retry, every attempt would await the same promise, which has already rejected.
Quick Reference
| Mistake | Symptom | Fix |
|---|---|---|
| No `return` in a `then` block | Next step gets `undefined` | Return the value or promise |
| Nested `then` | Outer `catch` misses inner errors | Flatten the chain, or use `async`/`await` |
| `return promise` inside `try` | `catch` never runs | `return await promise` |
| Missing `await` | Code runs early, rejection is unhandled | Add `await` or `.catch` |
| Independent sequential awaits | Total time is the sum of all steps | `Promise.all` |
| `async` callback in `forEach` | Function returns before work finishes | `for...of` or `Promise.all(map(...))` |
| Wrapping a promise in `new Promise` | Rejections lost | Chain on the original promise |
| `then(ok, fail)` as a safety net | Errors from `ok` slip through | Trailing `.catch` |
| Passing a promise where a function is needed | Retries reuse the failed result | Pass a function that returns a promise |
Exercise
This function should return the number of posts, but it logs "count: undefined". Find the cause and fix it: function countPosts(id) { return loadUser(id).then((user) => { loadPosts(user).then((posts) => posts.length); }); } countPosts(1).then((n) => console.log('count:', n));
Show answer
The outer handler has a block body with no return, so it returns undefined, and the inner promise is detached. Return the chain and flatten it: function countPosts(id) { return loadUser(id).then((user) => loadPosts(user)).then((posts) => posts.length); }. This logs "count: 1".
Exercise
An async function does const a = await fetchA(); const b = await fetchB(); return a + b;. fetchA takes 300 ms and fetchB takes 200 ms, and neither depends on the other. How long does it take, and how do you make it faster while still rejecting if either one fails?
Show answer
About 500 ms, because the awaits run one after the other. Use const [a, b] = await Promise.all([fetchA(), fetchB()]); return a + b;, which takes about 300 ms. It rejects as soon as either promise rejects.
Exercise
Inside try { return fetchData(); } catch { return fallback; } in an async function, fetchData() rejects. Does the caller get the fallback? Why or why not?
Show answer
No. The function returns the pending promise and leaves the try block before the promise rejects. The returned promise adopts the rejection, so the caller sees the error. Writing return await fetchData(); makes the rejection throw inside try, so the catch returns the fallback.