in Javascript, Software Development

Working with callbacks in Javascript

I am playing with the sample code for Dave Winer’s feedRead Github repo, and wanted to refactor one of the examples. I have seen multiple examples of a callback function source code included in a call to another function, but I wanted to have it be a separate function. Here is the example code:
[cc lang=”javascript”]
feedRead.parseUrl (urlTestFeed, timeOutSecs, function (err, theFeed) {
if (err) {
console.log (err.message);
}
else {
console.log (“It took ” + utils.secondsSince (whenstart) + ” seconds to read and parse the feed.”);
console.log (“theFeed.head == ” + utils.jsonStringify (theFeed.head));
console.log (“theFeed.items [0] == ” + utils.jsonStringify (theFeed.items [0]));
for (var i = 0; i < theFeed.items.length; i++) {
console.log (“Item #” + utils.padWithZeros (i, 2) + “: ” + theFeed.items [i].title + “.”);
}
}
});
[/cc]
After some experimenting, I figured out that all I needed in the feedRead.parseUrl call was the function name (with no parameters, even though it had parameters), and then the function could be factored out:

[cc lang=”javascript”]
feedRead.parseUrl (urlTestFeed, timeOutSecs, myparser);

function myparser (err, theFeed) {
if (err) {
console.log (err.message);
}
else {
console.log (“It took ” + utils.secondsSince (whenstart) + ” seconds to read and parse the feed.”);
console.log (“theFeed.head == ” + utils.jsonStringify (theFeed.head));
console.log (“theFeed.items [0] == ” + utils.jsonStringify (theFeed.items [0]));
for (var i = 0; i < theFeed.items.length; i++) {
console.log (“Item #” + utils.padWithZeros (i, 2) + “: ” + theFeed.items [i].title + “.”);
}
}
}
[/cc]

Note that the function does not have a semicolon at the end, but the call to feedRead.parseUrl does…

References:

https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced

https://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Write a Comment

Comment