Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.4 — Callbacks and Callback Hell
JavaScript · Example 4 of 4

try...catch can't catch an error in a later callback

When the callback throws, the try is no longer on the call stack, so nothing catches it. Async errors must be passed along (as err) or handled with promises.

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.

01

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.

02

Wrap divideLater in divideAsync(a, b) that returns a promise, and use it with .then and .catch.

Explain it without notes

01

What is an error-first callback, and why does that convention exist?

02

What is callback hell, and what problems does it cause beyond indentation?

03

Explain inversion of control with callbacks, and how promises address it.

04

Why can't try...catch around setTimeout catch an error thrown in its callback?

try...catch can't catch an error in a later callback

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

try block finished without errors
Uncaught Error: thrown inside the timer callback