Error-First vs Throwing Exceptions
You'll learn why asynchronous JavaScript uses error-first callbacks instead of try/catch blocks.
The Problem with Try/Catch in Async Code
When you write synchronous code, try/catch works perfectly — if something throws an error, the catch block immediately handles it. But asynchronous code doesn't execute immediately; it runs later, on a future tick of the event loop.
By the time your callback runs, the original try/catch block has already finished executing and is gone from the call stack. The error has nowhere to go, so it becomes an uncaught exception.
Why Error-First Callbacks Solve This
The error-first callback pattern passes errors as values (the first parameter) instead of throwing them. This means:
- The error arrives at the same time as your callback executes
- You can handle it right there in the callback function
- No try/catch timing mismatch
Think of it like this: throwing an exception is like shouting for help immediately. But if you're calling for help in a future you haven't reached yet, no one hears you. Error-first callbacks are like carrying a note with you that says "here's what went wrong" — it travels through time with your callback.
The Pattern in Action
// Try/catch can't catch this async error
try {
setTimeout(() => {
throw new Error("Too late!"); // Uncaught!
}, 100);
} catch (err) {
// Never runs
}
// Error-first callback delivers the error when it matters
setTimeout((err) => {
if (err) {
console.error("Caught:", err); // Works!
return;
}
console.log("Success");
}, 100);
Key Takeaway: Asynchronous code uses error-first callbacks because thrown exceptions can't be caught outside the async boundary — errors must be passed as values to arrive when the callback actually executes.