Callbacks explained in 3 minutes

Adrienne Tran
Jul 24, 2017 · 2 min read

To understand callbacks, we’re going to use an example that gets a file from the file system and displays the content in the file to the user.

We’ll start by building out the helper function. We can use filesystem, a library for Node.js that allows you to work with the file system. readFile takes two parameters: a file path and a callback.

fs.readFile(filePath, callback);

What does readFile do with the callback function? Let’s look at the callback itself. A callback function generally takes in two arguments: an error and the data. Why the term callback? The function will read the file at the filePath, and then call the callback function when it’s done. Specifically, it will invoke the callback with an error if there was one, else the file’s contents if the file data was successfully retrieved.

var callback = (err, data) => {
if (err) {
callback(err, null)
}
callback(null, data)
}

We put these two together in a helper function:

var getFileData = (url, callback) => {
fs.readFile(filePath, (err, content) => {
if (err) {
callback(false)
} else {
callback(content)
}
}
}

Finally, we invoke our callback getFileData where another function needs the file data before proceeding (hence the term asynchronous).

One such case is when a user is making a GET request to load a page and we want to display a file’s contents to them. In the request handler, we can call this textInFile function and don’t execute our next line of code until we receive the file’s contents.

var filePath = "~/index.txt";handleRequest = (req, res) => {
if (req.url === '/') {
if (req.method === 'GET') {
getFileData(filePath, (err, content) => {
res.writeHead(200)
res.end(content)
}
}
}
}

Imagine if we didn’t have callbacks and we tried to write this code in a synchronous manner. Our code would be trying to get file data that has not yet been retrieved. Callbacks allow us to more control over the execution of our code, so we can tell pieces to only execute once a dependency is ready.

Adrienne Tran

Product @ Tesla. Ex-Google, Ex-Bridgewater.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade