Callback functions
suggest changeCallback functions in JavaScript
Callback functions are common in JavaScript. Callback functions are possible in JavaScript because functions are first-class citizens.
Synchronous callbacks.
Callback functions can be synchronous or asynchronous. Since Asynchronous callback functions may be more complex here is a simple example of a synchronous callback function.
// a function that uses a callback named `cb` as a parameter
function getSyncMessage(cb) {
cb("Hello World!");
}
console.log("Before getSyncMessage call");
// calling a function and sending in a callback function as an argument.
getSyncMessage(function(message) {
console.log(message);
});
console.log("After getSyncMessage call");
The output for the above code is:
> Before getSyncMessage call
> Hello World!
> After getSyncMessage call
First we will step through how the above code is executed. This is more for those who do not already understand the concept of callbacks if you do already understand it feel free to skip this paragraph. First the code is parsed and then the first interesting thing to happen is line 6 is executed which outputs Before getSyncMessage call to the console. Then line 8 is executed which calls the function getSyncMessage sending in an anonymous function as an argument for the parameter named cb in the getSyncMessage function. Execution is now done inside the getSyncMessage function on line 3 which executes the function cb which was just passed in, this call sends an argument string “Hello World” for the param named message in the passed in anonymous function. Execution then goes to line 9 which logs Hello World! to the console. Then the execution goes through the process of exiting the callstack (see also) hitting line 10 then line 4 then finally back to line 11.
Some information to know about callbacks in general:
- The function you send in to a function as a callback may be called zero times, once, or multiple times. It all depends on implementation.
- The callback function may be called synchronously or asynchronously and possibly both synchronously and asynchronously.
- Just like normal functions the names you give parameters to your function are not important but the order is. So for example on line 8 the parameter
messagecould have been namedstatement,msg, or if you’re being nonsensical something likejellybean. So you should know what parameters are sent into your callback so you can get them in the right order with proper names.
Asynchronous callbacks.
One thing to note about JavaScript is it is synchronous by default, but there are APIs given in the environment (browser, Node.js, etc.) that could make it asynchronous (there’s more about that here).
Some common asynchronous APIs that accept callbacks:
- Events
setTimeoutsetInterval- many Node.js core APIs, such as
fs.readFile
fetch and promises are also asynchronous, but they settle a promise instead of taking an error-first callback. Wrapping a promise in a function that takes a callback is usually an anti-pattern.
So given that information we can construct an asynchronous function similar to the above synchronous one.
// a function that uses a callback named `cb` as a parameter
function getAsyncMessage(cb) {
setTimeout(function () { cb("Hello World!") }, 1000);
}
console.log("Before getSyncMessage call");
// calling a function and sending in a callback function as an argument.
getAsyncMessage(function(message) {
console.log(message);
});
console.log("After getSyncMessage call");
Which prints the following to the console:
> Before getSyncMessage call
> After getSyncMessage call
// pauses for 1000 ms with no output
> Hello World!
Execution starts at the first console.log, which prints Before getSyncMessage call. It then calls getAsyncMessage with a callback for cb. That function calls setTimeout with a callback and 1000. setTimeout keeps the callback and returns immediately, so execution continues through After getSyncMessage call and then waits. After one second, setTimeout calls its callback, which calls cb("Hello World!"), and that string is logged.
Callback functions in Node.js
Node.js callbacks are usually asynchronous and often pass an error-first pair, conventionally called err and data. This example reads a text file. Node.js core callbacks use that error-first convention: the first argument is an error or null.
const fs = require("fs");
fs.readFile("./test.txt", "utf8", function(err, data) {
if(err) {
// handle the error
} else {
// process the file text given with data
}
});
This is an example of a callback that is called a single time.
Handle the error even if you only log it or throw it. The else is unnecessary if you return or throw in the if, which also keeps the rest of the function from running.
Though it may be common to see err, data it may not always be the case that your callbacks will use that pattern it’s best to look at documentation.
Another example callback comes from the express library (express 4.x):
// this code snippet was on http://expressjs.com/en/4x/api.html
const express = require('express');
const app = express();
// this app.get method takes a url route to watch for and a callback
// to call whenever that route is requested by a user.
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000);
This example shows a callback that is called multiple times. The callback is provided with two objects as params named here as req and res these names correspond to request and response respectively, and they provide ways to view the request coming in and set up the response that will be sent to the user.
As you can see there are various ways a callback can be used to execute sync and async code in JavaScript and callbacks are very ubiquitous throughout JavaScript.