What is a callback
suggest changeThis is a normal function call:
console.log("Hello World!");
When you call a normal function, it does its job and then returns control back to the caller.
However, sometimes a function needs to return control back to the caller in order to do its job:
[1,2,3].map(function double(x) {
return 2 * x;
});
In the above example, the function double is a callback for the function map because:
- The function
doubleis given to the functionmapby the caller. - The function
mapneeds to call the functiondoublezero or more times in order to do its job.
Thus, the function map is essentially returning control back to the caller every time it calls the function double. Hence, the name “callback”.
Functions may accept more than one callback:
promise.then(function onFulfilled(value) {
console.log("Fulfilled with value " + value);
}, function onRejected(reason) {
console.log("Rejected with reason " + reason);
});
Here then function then accepts two callback functions, onFulfilled and onRejected. Furthermore, only one of these two callback functions is actually called.
What’s more interesting is that the function then returns before either of the callbacks are called. Hence, a callback function may be called even after the original function has returned.