Callback functions have been around since the early days of JavaScript, but there have never been any standards for using them. How should callbacks be passed into async APIs? How should errors that occur during async processing be handled? A lack of standards led to variations in API implementations.
The developers of Node.js decided that some basic rules for callbacks would be good for consistency. Today, the Node.js callback pattern is the canonical pattern used for async APIs (though some EventEmitter based APIs exist as well). Because the pattern is so simple, it’s very easy to learn and put to use. But, as we’ll see, the pattern alone isn’t perfect for every situation.
Please Note: This post is part of a series on working with database connections using various asynchronous patterns. See that post for more details and links to other options.
Callback pattern overview
The callback pattern in Node.js follows two basic rules:
- When an asynchronous API is invoked, the callback function will be the last parameter passed in.
- When the callback function is invoked, the first parameter is reserved for an error that may have occurred. The value will be null (falsy) if no error occurred and an instance of Error (truthy) if an error did occur.
Here’s a fictitious example that demonstrates the callback pattern:
const asyncFunc = require('asyncFunc');
function myCallback(err, value) {
if (err) {
// handle error
return; // Returning here is important!
}
// Do something with value
}
asyncFunc('foo', 42, myCallback);
This is what’s happening in the script above:
- Line 1: A fake async API is required in. This API is a function that implements the Node.js callback pattern.
- Lines 3-10: A function named myCallback is declared. The first formal parameter is reserved for errors that may occur when the async work is running (rule #2 above). The return statement on line 6 is used to exit the function after the error is handled.
- Line 12: The asyncFunc function is invoked. The last parameter passed in is a reference to the callback function (rule #1 above). When the async work is done, the callback will be added to the callback queue and eventually executed on the main thread.
Remember: If an error has occurred, it’s important to exit the function after handling the error. With this pattern, that responsibility falls on you.
As you can see, this is a pretty simple pattern and it works great for simple, sequential async flows. But, in addition to forgetting to exit after error handling logic, there are a couple of other issues that might trip up newcomers to Node.js.
Callback hell
Callback hell (a.k.a. the pyramid of doom) is something of a right of passage with Node.js. You start by writing one async call using an anonymous callback. Then you embed another async call, and then another, and you continue doing this until even you can’t make sense of the code anymore.
The following script, which writes a file, is a not-so-bad example of callback hell:
const fs = require('fs');
fs.open('test.txt', 'a+', function(err, fd) {
if (err) {
throw err;
}
fs.write(fd, 'test line', function(err, written, string) {
if (err) {
throw err;
}
fs.close(fd, function (err) {
if (err) {
throw err; // The top of the pyramid!
}
});
});
});
Do you see how each async call is indented to help keep the code readable? To some, the whitespace that builds up to the innermost async call looks like a horizontal pyramid (I used 4 spaces for indentation over 2 to make this effect more obvious). Welcome to the pyramid of doom!
Thankfully, the solution to this problem is simple: use named functions over anonymous functions! Here’s the same basic logic, rewritten using named functions.
const fs = require('fs');
function openFile() {
fs.open('test.txt', 'a+', function(err, fd) {
if (err) {
throw err;
}
writeFile(fd);
});
}
function writeFile(fd) {
fs.write(fd, 'test line', function(err, written, string) {
if (err) {
throw err;
}
closeFile(fd);
});
}
function closeFile(fd) {
fs.close(fd, function (err) {
if (err) {
throw err;
}
});
}
openFile();
Okay, so there are more lines of code in this version. But in the real world, using named functions leads to code that’s more readable, maintainable, composable, etc. Plus, we can limit the level of indentation, thus avoiding callback hell!
However, there are still situations where the callback pattern alone isn’t enough.
Callback pattern limitations
While the callback pattern is easy to use, there are lots of asynchronous workflows that it doesn’t help with out-of-the-box. Here are some examples:
- You need to run multiple asynchronous functions concurrently, then run a different function when the concurrent functions have finished.
- You need a queue that can run n number of functions concurrently.
- You have an array of “things” that needed to be processed asynchronously (either serially or in parallel), then run another function after all elements in the array have been processed.
Although the sample application in this series doesn’t do anything this complex, these types of flows are quite common. All of the tools you need to write such flows using just callbacks are available to you in JavaScript, but writing the algorithms may not be so easy and the resulting code may not be easy to maintain – especially for folks that are new to Node.js.
You might start writing a library to abstract away some of the complexity involved with such async flows. If you spent a lot of time building out such a library, you’d eventually have something that looks a lot like Async, one of the most popular libraries in the history of Node.js. We’ll cover Async in the next post in this series. For now, let’s stick to the callback pattern and see how it can be used to code the demo application.
Callback demo app
The callback demo app is comprised of the following four files. The files are also available via this Gist.
{
"name": "callbacks",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Dan McGhan <[email protected]> (https://jsao.io/)",
"license": "ISC",
"dependencies": {
"oracledb": "^1.13.1"
}
}
This is a very basic package.json file. The only external dependency is oracledb.
const oracledb = require('oracledb');
const dbConfig = require('./db-config.js');
const employees = require('./employees.js');
oracledb.createPool(dbConfig, function(err) {
if (err) {
console.log(err);
return;
}
employees.getEmployee(101, function(err, emp) {
if (err) {
console.log(err);
return;
}
console.log(emp);
});
});
In this version of the index.js, the Node.js callback pattern is used to first create a connection pool and then to fetch an employee. Although the pool is passed to the callback function for createPool, it’s not referenced here as the built-in pool cache will be used in employees.js.
module.exports = {
user: 'hr',
password: 'oracle',
connectString: '192.168.56.101:1521/orcl',
poolMax: 20,
poolMin: 20,
poolIncrement: 0
};
The db-config.js file is used in index.js to provide the connection info for the database. This configuration should work with the DB App Dev VM, but it will need to be adjusted for other environments.
const oracledb = require('oracledb');
function getEmployee(empId, getEmployeeCallback) {
oracledb.getConnection(function(err, conn) {
if (err) {
console.log('Error getting connection', err);
getEmployeeCallback(err);
return;
}
console.log('Connected to database');
conn.execute(
`select *
from employees
where employee_id = :emp_id`,
[empId],
{
outFormat: oracledb.OBJECT
},
function(err, result) {
if (err) {
console.log('Error executing query', err);
getEmployeeCallback(err);
conn.close(function(err) {
if (err) {
console.log('Error closing connection', err);
} else {
console.log('Connection closed');
}
});
return;
}
console.log('Query executed');
getEmployeeCallback(null, result.rows[0]);
conn.close(function(err) {
if (err) {
console.log('Error closing connection', err);
} else {
console.log('Connection closed');
}
});
}
);
});
}
module.exports.getEmployee = getEmployee;
This version of the employees.js file uses the Node.js callback pattern to get a connection, use it to execute a query, and then close the connection. Notice that the logic to close the connection, the “finally” in the try…catch…finally block, appears twice: once if an error occurs during the call to connection.execute and again if everything completes without error. The code could be refactored so that the “close” logic is only defined once, but it would still need to be called from these two locations.
The Node.js callback pattern is important to understand when working with Node.js. It’s simple but effective. Hopefully, you now have a better understanding of how it works. Check out the next part of the series to see how to use the Async module to do the same work.