Coding Techniques
Callbacks · Study material
Flattening callback hell with named functions
Give every step a name and pass the next step as its callback. The flow reads top to bottom and each function handles its own errors:
// Flatten callback hell by giving each step a name and a single job
function step(name, value, cb) { setTimeout(() => cb(null, `${value} → ${name}`), 0); }
function validate(order) { step("validate", order, charge); }
function charge(err, order) { if (err) return fail(err); step("charge", order, ship); }
function ship(err, order) { if (err) return fail(err); step("ship", order, done); }
function done(err, order) { if (err) return fail(err); console.log(order); }
function fail(err) { console.log("Failed:", err.message); }
validate("order #7");
order #7 → validate → charge → ship
try/catch cannot catch async errors
By the time an async callback throws, the surrounding try block has long finished. Catch errors inside the callback and pass them on through the error-first argument:
// try/catch only catches errors thrown while the try block is running.
// An async callback runs later, outside it – so report errors through the callback instead.
function loadSettings(cb) {
setTimeout(() => {
try {
const data = JSON.parse("{ bad json }");
cb(null, data);
} catch (e) {
cb(e); // pass the error to the caller
}
}, 0);
}
try {
loadSettings((err) => console.log(err ? `callback got ${err.name}` : "ok"));
console.log("try block finished – nothing thrown yet");
} catch {
console.log("never reached");
}
try block finished – nothing thrown yet callback got SyntaxError
Callbacks vs promises
| Callbacks | Promises | |
|---|---|---|
| Sequencing | nesting | flat .then chains / await |
| Errors | checked in every callback | one .catch / try…catch |
| Called how many times? | up to the caller (could be 0 or 2) | settles exactly once |
| Running in parallel | manual counters | Promise.all |
| Still the right tool for | array methods, events, streams | one-off asynchronous results |
Callbacks checklist
- Pass functions, not function calls.
- Follow error-first for async callbacks and always return after handling an error.
- Make an API always async (or always sync), never both.
- Store parallel results by index.
- Guard callbacks you hand to untrusted code (once, timeouts).
- Convert repeated nesting to promises or async/await.