Sub topic 14
Common Mistakes: Forgotten Returns, Sequential Awaits and More
This chapter assumes you already know how promise chains pass values along, how catch handles errors, how Promise.all works, and how to write async functions with await. Most promise bugs don't throw errors. The code runs, but in the wrong order, too slowly, or with a value of undefined. The mistakes below cause most of those bugs.
Forgetting to Return Inside then
A then handler passes on whatever it returns. If you start a promise inside the handler and don't return it, the next step gets undefined and runs straight away. It does not wait for that promise.
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
delay(50, 1)
.then((n) => {
delay(50, n + 1); // promise created but not returned
})
.then((n) => console.log('broken:', n)); // broken: undefined
delay(50, 1)
.then((n) => delay(50, n + 1)) // returned, so the chain waits
.then((n) => console.log('fixed:', n)); // fixed: 2An arrow function with a block body ({ ... }) needs an explicit return. An arrow function with an expression body returns its value automatically.
Accidental Sequential Awaits
Each await pauses the function until that promise settles. If you await independent tasks one at a time inside a loop, each task starts only after the previous one has finished.
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
const fetchUser = (id) => delay(100, { id });
async function slow(ids) {
const users = [];
for (const id of ids) {
users.push(await fetchUser(id)); // about 100 ms per id
}
return users;
}
async function fast(ids) {
return Promise.all(ids.map((id) => fetchUser(id))); // about 100 ms total
}
async function main() {
console.time('slow');
await slow([1, 2, 3]);
console.timeEnd('slow'); // roughly 300 ms
console.time('fast');
await fast([1, 2, 3]);
console.timeEnd('fast'); // roughly 100 ms
}
main();Run tasks one after another only when a step needs the previous result, or when you must limit load on a server.
Using async Callbacks with forEach
forEach ignores the values its callback returns. An async callback returns a promise, and forEach drops it, so nothing waits for that promise to settle. A rejection inside the callback is also not caught by any surrounding try/catch.
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
async function main() {
[1, 2, 3].forEach(async (id) => {
await delay(50);
console.log('forEach done', id);
});
console.log('after forEach'); // prints before any "done"
for (const id of [1, 2, 3]) {
await delay(50);
console.log('for...of done', id); // runs in order, awaited
}
await Promise.all([1, 2, 3].map(async (id) => {
await delay(50);
console.log('map done', id); // concurrent, awaited
}));
}
main();Wrapping a Promise in new Promise
Don't wrap code that already returns a promise in new Promise. The extra layer adds no value, and it is easy to forget to call reject, which leaves the outer promise pending forever.
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
// Anti-pattern: errors from delay are never passed to reject
function getBad() {
return new Promise((resolve) => {
delay(10, 'data').then((v) => resolve(v));
});
}
// Better: return the existing promise directly
function getGood() {
return delay(10, 'data').then((v) => v.toUpperCase());
}
getGood().then(console.log); // DATAUse the constructor only to wrap APIs that don't return promises, such as timers or callback-based functions.
Floating Promises
A floating promise is one that nobody awaits, returns, or attaches a catch to. If it rejects, the result is an unhandled rejection. Every promise should end in one of three places: a returned value, an await inside a try/catch, or a .catch() handler.
| Mistake | Symptom | Fix |
|---|---|---|
| Missing `return` in `then` | Next step gets `undefined` | Return the value or promise |
| `await` in a loop | Slow total time | `Promise.all` with `map` |
| `async` callback in `forEach` | Code continues before work finishes | `for...of` or `Promise.all` |
| Wrapping a promise in `new Promise` | Errors lost, promise hangs | Return the existing promise |
| Floating promise | Unhandled rejection | `await`, `return`, or `.catch()` |
Exercise
This function should return the totals for all orders, but it returns an empty array. Why, and how would you fix it so the orders load concurrently? async function totals(ids) { const out = []; ids.forEach(async (id) => { out.push(await loadOrder(id)); }); return out; }
Show answer
forEach drops the promises returned by the async callback, so the function returns out before any loadOrder call finishes. Use Promise.all: async function totals(ids) { return Promise.all(ids.map((id) => loadOrder(id))); }. This starts every load at once, waits for all of them, and keeps the results in the same order as ids.
Exercise
What does this log, and why? Promise.resolve(5).then((n) => { n * 2; }).then((n) => console.log(n));
Show answer
It logs undefined. The first handler has a block body with no return statement, so it returns undefined, and the next handler receives that value. Write (n) => n 2 or add return n 2.