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, map calls double, the function the caller provided. 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 the function then accepts two callback functions, onFulfilled and onRejected. If the promise settles, only one of them is called. If it stays pending, neither is 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.