HomeOur TeamContact
NodeJS
Functions in NodeJS
Nisar
Nisar
May 16, 2021
1 min

There are two type of functions in NodeJS

  • Asynchronous (non-blocking functions)
  • Synchronous (blocking functions)

Error-first callbacks

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
});

Callback Function

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.

Difference between returning a callback and just calling a callback

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

Example

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}`);

Output

[0] Execute function: do2
[0] print do2 callback param
[0] print return from callback(do2 callback param)

Event Listeners

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.


Next Article
Use Cases of combination operators in RxJS
Nisar

Nisar

© 2021, All Rights Reserved.

Quick Links

Advertise with usAbout UsContact Us

Social Media