There are two type of functions in NodeJS
Error-first callbacks is a function whose first parameter is error and then data. Here programmer has to check if something went wrong in the beginning of the function.
fs.readFile(filePath, function(err, data) { if (err) { //handle the error } // use the data object });
A callback function is called at the completion of a given task. All APIs of Node are written is such a way that they supports callbacks. This type of function makes NodeJS highly scalable
For example, a function to read a file may start reading file and return the control to execution environment immediately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O.
Returning will return the execution from the callback function but callback function will move to next line to execute the code. Returning will help the context calling async function get the value returned by callback.
return callback(); //some more lines of code; - won't be executed callback(); //some more lines of code; - will be executed
function do2(callback) { log.trace('Execute function: do2'); return callback('do2 callback param'); } var do2Result = do2((param) => { log.trace(`print ${param}`); return `return from callback(${param})`; // we could use that return }); log.trace(`print ${do2Result}`);
[0] Execute function: do2 [0] print do2 callback param [0] print return from callback(do2 callback param)
Event Listeners are similar to call back functions but are associated with some event. For example when a server listens to http request on a given port a event will be generated and to specify http server has received and will invoke corresponding event listener.
Quick Links
Legal Stuff