I am using the async library and am using the async.waterfall function whose signature is async.waterfall([function1,function2,function3],function(err,result){}). Now i understand that the results of each function is passed on to the next and the final callback function is executed in case of some error in between or when the execution is over.
What i do not understand is that each function in the array of functions passed takes a callback as an argument and the callback is executed in each function with the result of that function. But i do not understand where that callback function is defined.
Below is a sample piece of code
async.waterfall([ function getUserAvatar(callback) { console.log("Callback function is " + callback)//print the callback definition function github.search.users({ q: 'airbnb' }, function(err, res) { if (err) { callback(err, null); return; } var avatarUrl = res.items[0].avatar_url; callback(null, avatarUrl); }); }, function wrapAvatarInHtml(avatarUrl, callback) { var avatarWithHtml = '<img src="' + avatarUrl + '"/>'; callback(null, avatarWithHtml); } ], function(err, result) { if (err) { console.error(err); return; } console.log(result); }) When i execute the above code, the line where i do console.log("Callback function is " + callback) it prints the below definition.
function () { if (fn === null) throw new Error("Callback was already called."); var callFn = fn; fn = null; callFn.apply(this, arguments); } Now i do not understand where it is getting this definition. I searched the async library also for this but i could not find it. Can anyone explain this.
waterfallthat calls your functions with its own callback function. It needs to do that so it gets notified of the asynchronous success/error event and can then take action within its own callback to trigger the next function in the waterfall, etc.onlyOncefunction - github.com/caolan/async/blob/master/dist/async.js#L298