Async Mistakes and Debugging
Asynchronous code fails in ways synchronous code can't: a value is used before it exists, an error disappears without a trace, two operations finish in the wrong order, or a loop "finishes" before its work has started. This lesson collects the async mistakes that cause most real bugs, shows each one failing for real, gives the fix, and ends with how to debug and test async code with node:test.
In One Minute
- Forgotten
awaitgives you a promise instead of a value, and lets errors escapetry...catch. forEachwith anasynccallback doesn't wait; usefor...oforPromise.all(arr.map(...)).- Unhandled rejections crash Node.js and hide failures in browsers; every promise needs a handler.
- Accidental sequential awaits make independent work slow; race conditions let stale results win.
- Debug with async stack traces in DevTools; test with
asynctest functions andassert.rejects.
Mistake 1: Forgetting await
Without await, you get the promise, not its value:
async function getBalance() {
return 120;
}
const wrong = getBalance();
console.log(wrong, "|", wrong + 30);
const right = await getBalance();
console.log(right, "|", right + 30);{} | [object Promise]30
120 | 150Explanation: wrong is a pending promise (this site's console prints it as {}; Node.js shows Promise { 120 }), and wrong + 30 converts it to the string "[object Promise]". The bug often surfaces far from its cause, as strange strings or undefined properties.
A forgotten await also breaks error handling: the try block finishes before the promise rejects, so the catch never sees the error:
async function save() {
await new Promise((r) => setTimeout(r, 5));
throw new Error("Save failed");
}
async function wrong() {
try {
return save();
} catch {
return "handled";
}
}
async function right() {
try {
return await save();
} catch {
return "handled";
}
}
console.log(await right());
console.log(await wrong().catch((err) => `escaped the try: ${err.message}`));handled
escaped the try: Save failedreturn save() inside a try returns the promise immediately, leaving the try; the rejection happens later, outside it. return await save() waits inside the try.
Mistake 2: forEach with async
forEach calls the callback for each item and ignores what it returns, including promises. It doesn't wait:
const save = (id) => new Promise((resolve) => setTimeout(() => resolve(id), 10));
const saved = [];
[1, 2, 3].forEach(async (id) => {
saved.push(await save(id));
});
console.log("after forEach:", saved.length, "saved");
await new Promise((r) => setTimeout(r, 30));
console.log("later:", saved.length, "saved");
const results = [];
for (const id of [1, 2, 3]) results.push(await save(id));
console.log("for...of:", results);
console.log("Promise.all:", await Promise.all([1, 2, 3].map((id) => save(id))));after forEach: 0 saved
later: 3 saved
for...of: [1, 2, 3]
Promise.all: [1, 2, 3]The code after forEach ran before a single save finished, and if a save rejected, nothing would catch it. The same applies to map without Promise.all, filter with an async predicate (a promise is always truthy, so nothing is filtered), and reduce with an async callback.
| Need | Use |
|---|---|
| One at a time, in order | for (const x of items) await fn(x) |
| All at once | await Promise.all(items.map(fn)) |
| Async filter | const keep = await Promise.all(items.map(test)); items.filter((_, i) => keep[i]) |
Mistake 3: Unhandled Rejections
A promise that rejects with no handler attached is an unhandled rejection. Browsers log an error in the console; Node.js prints the error and exits with a failure code:
process.on("unhandledRejection", (reason) => {
console.log("Unhandled rejection caught by the safety net:", reason.message);
});
async function sendReceipt() {
throw new Error("SMTP server unreachable");
}
sendReceipt();
console.log("script continues, unaware");script continues, unaware
Unhandled rejection caught by the safety net: SMTP server unreachableHere a global unhandledRejection listener caught it; without one, Node.js would have crashed the process. A global handler (in browsers, window.addEventListener("unhandledrejection", ...)) is a safety net for logging, not a replacement for handling errors where they happen.
Mistake 4: Accidental Sequential Code
Independent awaits in a row wait for each other:
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const start = Date.now();
const student = await wait(40, "Navika");
const settings = await wait(40, "USD");
console.log(`sequential: about 80 ms? ${Date.now() - start >= 75}`);
const t = Date.now();
const [s2, c2] = await Promise.all([wait(40, "Navika"), wait(40, "USD")]);
console.log(`parallel: under 70 ms? ${Date.now() - t < 70}`, s2 === student && c2 === settings);sequential: about 80 ms? true
parallel: under 70 ms? true trueWhen reviewing async code, ask for each await: "does the next line need this result?" If not, start the operations together.
Mistake 5: Race Conditions
A race condition is a bug where the result depends on which async operation finishes first. Two classic forms: stale responses (an older request finishes after a newer one), and lost updates (two operations read the same value, each changes it, and one overwrites the other):
let balance = 450;
const read = async () => { await new Promise((r) => setTimeout(r, 5)); return balance; };
const write = async (v) => { await new Promise((r) => setTimeout(r, 5)); balance = v; };
async function payUnsafe(amount) {
const current = await read();
await write(current - amount);
}
await Promise.all([payUnsafe(100), payUnsafe(50)]);
console.log("unsafe balance:", balance);
balance = 450;
let queue = Promise.resolve();
function paySafe(amount) {
queue = queue.then(async () => {
const current = await read();
await write(current - amount);
});
return queue;
}
await Promise.all([paySafe(100), paySafe(50)]);
console.log("safe balance:", balance);unsafe balance: 400
safe balance: 300Explanation: both unsafe payments read 450 before either wrote, so the second write overwrote the first: $100 vanished. The safe version chains each payment onto the previous one, so they run one at a time. In real systems, the database should handle this (transactions, or an atomic balance = balance - $1); in the browser, aborting older requests (see the cancellation lesson) fixes stale responses.
Mistake 6: Mixing Callbacks and Promises Badly
function loadLater(callback) {
setTimeout(() => callback(null, [120, 85]), 5);
}
async function wrong() {
let data;
loadLater((err, d) => { data = d; });
return data;
}
function right() {
return new Promise((resolve, reject) => loadLater((err, d) => (err ? reject(err) : resolve(d))));
}
console.log(await wrong(), await right());undefined [120, 85]Assigning from a callback into an outer variable and returning it doesn't wait. Wrap callback APIs in a promise (or use util.promisify in Node.js), then await it.
Debugging Async Code
Async stack traces. Chrome DevTools, VS Code and Node.js show the chain of await calls that led to an error, labeled await in or "async". They work best when you use async/await rather than long then chains.
async function loadPayments() {
await new Promise((r) => setTimeout(r, 1));
throw new Error("Payments API returned 500");
}
async function buildReport() {
return await loadPayments();
}
try {
await buildReport();
} catch (err) {
console.log(err.stack.split("\n").slice(0, 3).map((l) => l.trim().replace(/\(.*\//, "(")).join("\n"));
}Error: Payments API returned 500
at loadPayments (stack.js:3:9)
at async buildReport (stack.js:6:10)The second line of the trace shows async buildReport, even though buildReport wasn't on the call stack when the error was thrown: the engine recorded the await chain. (The example trims the file path to just the file name.)
| Debugging tool | Use |
|---|---|
| "Pause on caught exceptions" / "Pause on uncaught exceptions" in DevTools | Stop exactly where a promise rejects |
Breakpoints after await | Inspect values when the function resumes |
console.log with labels and timestamps | See the real order of events |
| Network panel (with throttling) | Reproduce slow and out-of-order responses |
unhandledrejection listener | Log every rejection nobody handled |
Testing Async Code
node:test supports async test functions: the test waits for the returned promise. Use assert.rejects for expected failures:
import { test } from "node:test";
import assert from "node:assert/strict";
async function lateFee(fetchDaysLate, studentId) {
const days = await fetchDaysLate(studentId);
if (days < 0) throw new RangeError("days late can't be negative");
return Math.min(Math.max(days - 10, 0) * 2, 30);
}
test("computes the fee from fetched data", async () => {
const fakeFetch = async () => 14;
assert.equal(await lateFee(fakeFetch, "S-1"), 8);
});
test("rejects bad data", async () => {
await assert.rejects(lateFee(async () => -1, "S-2"), RangeError);
});✔ computes the fee from fetched data (0.241375ms)
✔ rejects bad data (0.138166ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.434Passing the data-fetching function as a parameter (fetchDaysLate) lets the test supply a fake, so the test is fast and doesn't need a real server. assert.rejects must itself be awaited; forgetting that await makes the test pass without checking anything.
In Practice
A buggy Fee Tracker function with four async mistakes, and the corrected version:
const api = {
student: async (id) => ({ id, name: "Advitha", fee: 120 }),
payments: async () => [45, 30],
notify: async (name) => { if (!name) throw new Error("no name"); return `notified ${name}`; },
};
async function refreshStudent(id) {
try {
const [student, payments] = await Promise.all([api.student(id), api.payments(id)]);
const balance = student.fee - payments.reduce((a, b) => a + b, 0);
const results = await Promise.allSettled(payments.map(() => api.notify(student.name)));
return `${student.name} owes $${balance} (${results.length} notifications)`;
} catch (err) {
return `Could not refresh: ${err.message}`;
}
}
console.log(await refreshStudent(3));async function refreshStudent(id) {
try {
const student = await api.student(id); // sequential: payments could load in parallel
const payments = api.payments(id); // missing await: payments is a promise
const balance = student.fee - payments.reduce((a, b) => a + b, 0); // TypeError
payments.forEach(async () => api.notify(student.name)); // forEach doesn't wait
return refreshSummary(student, balance); // missing await inside try
} catch (err) {
return `Could not refresh: ${err.message}`;
}
}Advitha owes $45 (2 notifications)Common Mistakes
Every section above is a common mistake; in short: always await (and return await inside try), never use forEach with async, handle every rejection, start independent work in parallel, and guard shared state against races.
Practice
Challenge: This function should return the names of students who still owe money, but it returns everyone. Fix the async filter.
const owes = async (s) => s.balance > 0;
async function debtors(students) {
return students.filter(async (s) => await owes(s)).map((s) => s.name);
}Show solution
const owes = async (s) => s.balance > 0;
async function debtors(students) {
const flags = await Promise.all(students.map(owes));
return students.filter((_, i) => flags[i]).map((s) => s.name);
}
console.log(await debtors([{ name: "Navika", balance: 0 }, { name: "Srihitha", balance: 85 }]));['Srihitha']The original filter received a promise from the async callback, and every promise is truthy, so nothing was filtered out.
Key Takeaways
| Mistake | Fix |
|---|---|
Missing await | Add it; enable a lint rule for floating promises |
return promise in try | return await promise |
forEach(async ...) | for...of or Promise.all(arr.map(...)) |
| Fire and forget | .catch(logError) |
| Lost updates | Serialize, or let the database update atomically |
| Stale responses | Abort older requests |
Was this tutorial helpful?