Cloud Parts

Callbacks

Pass a function to the operation; the runtime calls it with the result when the work is done.

How they work

The oldest and simplest form. The caller hands the operation a function and moves on; when the data arrives, the runtime calls that function with it. Node.js adopted a convention for failures: the first parameter of every callback is the error object, null when there was none, so each callback starts by checking it.

The trouble starts when one step depends on another. Each dependent call nests inside the previous callback, and the Node.js docs show four levels of nesting as a mild case. Bob Nystrom points out what the closures are doing: because the caller’s stack is gone by the time the result arrives, every local variable the next step needs has to be captured and moved to the heap by hand. Rich Hickey’s critique is that callbacks tangle communication with flow of control, which is why handlers come with rules like “don’t do too much work in your handler”.

JavaScript answered with promises (ES2015) and async/await (ES2017). Callbacks still sit underneath almost every event loop and UI toolkit, and they’re fine for one-shot events such as a click handler.

Sources

Improve this page on GitHub