Error-first callbacks
The results arrive later, inside the callback. The same handle function deals with both outcomes because the error always comes first.
A callback is a function you pass to another function so it can call you back when a job finishes; it's the oldest way to handle async results, with an error-first convention, but nesting them gets messy and you must trust the code that calls them.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write divideLater(a, b, callback) that, after 50 ms, calls callback(new Error("Cannot divide by zero")) if b is 0, otherwise callback(null, a / b). Call it for 10 / 2 and 1 / 0.
Wrap divideLater in divideAsync(a, b) that returns a promise, and use it with .then and .catch.
Explain it without notes
What is an error-first callback, and why does that convention exist?
What is callback hell, and what problems does it cause beyond indentation?
Explain inversion of control with callbacks, and how promises address it.
Why can't try...catch around setTimeout catch an error thrown in its callback?
Preview
Console
Nothing logged yet.Expected console output
Both requests started
Loaded: { id: 7, name: 'User 7' }
Failed: Invalid id: -1