06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9<br />

What we changed was to wrap the asynchronous code in a getSiteStatus()<br />

function, pass a function named callback() as a parameter to this function, and<br />

execute this function on the last line of getSiteStatus(). The showStatusCode()<br />

callback function simply wraps around console.log() that we called earlier. The<br />

difference, however, is in the way the asynchronous execution works. The most<br />

important idea to understand while learning how to program with callbacks is that<br />

functions are first-class objects that can be stored in variables and passed around<br />

with different names. Giving simple and descriptive names to your variables is<br />

important in making your code readable by others. Now that the callback function<br />

is called once the HTTP call is completed, the value of the status_code variable<br />

will have a correct value. There are genuine circumstances where you want an<br />

asynchronous task executed only after another asynchronous task is completed.<br />

Consider this scenario:<br />

http.createServer(function (req, res) {<br />

getURL(url, function (err, res) {<br />

getURLContent(res.data, function(err,res) {<br />

...<br />

});<br />

});<br />

});<br />

As you can see, we are nesting one asynchronous function in another. This kind of<br />

nesting can result in code that is difficult to read and manage. This style of callback<br />

is sometimes known as callback hell. To avoid such a scenario, if you have code<br />

that has to wait for some other asynchronous code to finish, then you express that<br />

dependency by putting your code in functions that get passed around as callbacks.<br />

Another important idea is to name your functions instead of relying on anonymous<br />

functions as callbacks. We can restructure the preceding example into a more<br />

readable one as follows:<br />

var urlContentProcessor = function(data){<br />

...<br />

}<br />

var urlResponseProcessor = function(data){<br />

getURLContent(data,urlContentProcessor);<br />

}<br />

var createServer = function(req,res){<br />

getURL(url,urlResponseProcessor);<br />

};<br />

http.createServer(createServer);<br />

[ 209 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!