Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Short circuit function chains if an error occurs
var fs = require('fs');
// read a file
function read_the_file(filename, callback) {
// begin by reading a file
fs.readFile(filename, function (err, contents) {
// an error occurred, i.e. the file was not found.
// instead of throwing an error, skip the other
// functions and directly invoke the callback
// function and provide the error object
if (err) return callback(err);
// continue
read_data_from_db(null, contents, callback);
} // read_the_file()
// this function would hold the next step
function read_data_from_db(err, contents, callback) {
/* logic here */
} // read_data_from_db()
// this function call could originate from somewhere else
// in your code.
read_the_file('/some/file', function (err, result) {
// don't throw the error, just log it (just because)
if (err) {
// do something with the result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment