Hasani
Hasani

Reputation: 3929

How does callback functions work in NodeJS?

Considering the following code:

rectangle.js:

module.exports = (x,y,callback) => {
    if (x <= 0 || y <= 0)
        setTimeout(() => 
            callback(new Error("Rectangle dimensions should be greater than zero: l = "
                + x + ", and b = " + y), 
            null),
            2000);
    else
        setTimeout(() => 
            callback(null, {
                perimeter: () => (2*(x+y)),
                area:() => (x*y)
            }), 
            2000);
}

index.js:

var rect = require('./rectangle');

function solveRect(l,b) {
    console.log("Solving for rectangle with l = "
                + l + " and b = " + b);
    rect(l,b, (err,rectangle) => {
        if (err) {
            console.log("ERROR: ", err.message);
        }
        else {
            console.log("The area of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.area());
            console.log("The perimeter of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.perimeter());
        }
    });
    console.log("This statement after the call to rect()");
};

solveRect(2,4);
solveRect(3,5);
solveRect(0,5);
solveRect(-3,5);

In this line rect(l,b, (err,rectangle) we call the rect function and pass l,b, err,rectangle to it. I can see what are l,b but can't see and understand what are err, rectangle ?

Also can't understand where is the definition of callback function? Is it an inner function?

Upvotes: -1

Views: 148

Answers (2)

zfj3ub94rf576hc4eegm
zfj3ub94rf576hc4eegm

Reputation: 1273

The arrow notation can be confusing here, especially since it takes up most of the rect function call. It is equivalent to


var callback = function(err,rectangle){
  if(err) {
    // do stuff
  } else {
    // do stuff
  }
};

rect(l,b, callback);

When we call rect(l,b, callback) inside of index.js, it calls the function inside of rectangle.js, passing in a reference to the function in index.js (which i named callback above). This means that when rectangle calls callback(new Error( ... it is passing in an Error object to the callback defined in index.js. And when it calls callback(null, ... it is passing null for the err parameter and the rectangle object for the rectangle parameter in callback.

At the moment we call rect(l,b, callback) we don't have the err or rectangle parameters though, javascript just knows it's passing a function that takes 2 parameters.

Upvotes: 1

Callback is nothing but the concept of passing a function as a parameter in function call like solveRect(2,4, fn). Here fn is going to be a function.

You can define it inline:

solveRect(2,4, function(err,rectangle){
   // your code to handle response or delayed result
});

Or as named function:

let fn = function(err,rectangle){
   // your code to handle response or delayed result
}
solveRect(2,4,fn)

Upvotes: 1

Related Questions