Skip to the workspace
Pebellslearn by building
Asynchronous JavaScript  ›  Lesson

Callbacks and Callback Hell

Callbacks 12 min

javascript / Callbacks and Callback Hell

Explore each scene at your own pace.

01 · Callbacks and Callback Hell

Callbacks and Callback Hell

Callbacks and Callback Hell

A callback is a function passed to another operation to be invoked according to that operation’s contract. A callback is not necessarily asynchronous.

Passing instructions and calling them immediately are different actions.

See the mechanism

Walk through the modelCallbacks and Callback HellAuthored snapshots of the example; use Run below to test the code.
onPublishedcallback function
The receiving operation decides when to invoke it.
1 of 3

Follow one example

javascript

This publish implementation invokes its callback synchronously, so the publication message appears before After publish. Passing console.log(...) would execute that expression first instead of passing a function. Nested asynchronous callbacks can make sequencing and error handling hard to follow; promises offer another way to represent those eventual results.

Predict, change and check

Predict: Does passing a callback automatically move its work to another thread?

Test your explanation: Replace onPublished(...) with setTimeout(() => onPublished(...), 0), then predict the changed output order. The timer is supplied by the host, not by callback syntax itself.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

A callback is an input contract

Passing a function gives another operation behavior it can invoke later or immediately. A callback is not inherently asynchronous: Array.map calls its callback synchronously. A callback-style I/O API can instead invoke a handler in a later turn, according to its host contract.

Nested dependent callbacks can obscure ownership and error paths. Give each operation one clear completion policy, keep callback error conventions explicit, and do not both return a result and invoke a completion callback unless the API defines those two channels. Promises can organize eventual outcomes, but they do not make every underlying operation cancellable.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.