Callbacks to gather data in JavaScript

Callbacks may be a dying breed with the new ES6 inclusion of promises but it’s good to understand the need for a callback.

JavaScript by design is asynchronous to ensure speedy applications. This means that when a line of code is fired, it doesn’t wait for a response before executing the next line of code. But what happens if you need the first line to return in order to use the returned item for the next line of code? This is where callbacks come in most handy.

Creating a function that takes a callback as one of the arguments will provide scope and closure to the line of code that called the function. It’s like sending an enclosed stamped envelope along with your wedding invite in order to get a (reliable) response from the guest you are inviting.

This is really important when gathering data from a database or when the function you are calling parses a text file because these processes can take some time.

Here’s an example of a recent use case that helped my web historian read and return the index file:

http-helpers.js

exports.serveIndex = function(res, asset) {

archive.readIndex(function(data){

res.writeHead(200, this.headers);
res.end(JSON.stringify(data));

});

};

archive-helpers.js

exports.readIndex = function (callback) {

fs.readFile(exports.paths.index, "utf8", function(err, data){

if(err) throw err;

callback(data);

});

};

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s