Callbacks

A callback is a conventional approach to providing a way to hook into asynchronous tasks. A callback is simply a function that is passed to another function and is expected to be called at some later point, possibly immediately, possibility soon, and possibly never. Consider the following requestData function:

function requestData(path, callback) {  // (Implementation of requestData)}

As you can see, it accepts a callback as its second argument. When calling requestData, the callback will typically be anonymously passed inline, like so:

requestData('/data/123', (response) => { /* ... */ });

It is, of course, totally fine to have previously declared the callback, and doing so can aid comprehensibility as now the reader of your code ...

Get Clean Code in JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.