liveBook · Manning

Callback

As explained in Functional Programming in JavaScript

A programming pattern in which a function is passed to another operation to be invoked later, often for asynchronous control flow.

A callback is a function passed to another operation so it can be invoked later, usually after asynchronous data arrives or an event occurs. This avoids blocking the user interface, but reverses ordinary control flow: “Don’t call me, I’ll call you.” section 8.1

Fetching students asynchronously

A request returns before its data is ready, so passing showStudents as the success callback makes it run at the correct time: getJSON('/students', students => showStudents(students), error => console.log(error.message)). section 8.1

Callbacks also receive errors through a separate error callback. They work well for one asynchronous step, but sequential requests can produce deeply nested success and error handlers—the callback pyramid—which is difficult to read and scale. section 8.1

How Functional Programming in JavaScript covers it

How deep it goes
Explains timing, inversion of control, errors, nested callbacks, and loop closures, but stops short of a scalable asynchronous abstraction.
Examples
Uses XMLHttpRequest, student records, grades, button clicks, mouseover events, nested JSON calls, and a loop closure bug.
What it assumes
Assumes JavaScript functions and linear control flow while building asynchronous timing from AJAX examples.
What you can do after
Apply it via JavaScript callbacks to sequence asynchronous work, process returned data, and handle request errors.
How it connects
Connects callbacks with asynchronous programming, event-driven programming, closures, continuation-passing style, and functional programming.

Also explained in

Compare how 19 books explain callback →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.