Ken Kwok Ken Kwok - 4 months ago 9
Node.js Question

What does 'cb' mean in loopback?

I am trying to learn loopback but I don't really understand what 'cb' means in function call. I read this In loopback documentaion what does variable 'cb' stands for? and I have basic understanding of callback in nodejs but I just don't understand cb in loopback.
For example, http://docs.strongloop.com/display/public/LB/Remote+methods.

module.exports = function(Person){



Person.greet = function(msg, cb) {

cb(null, 'Greetings... ' + msg);

}



Person.remoteMethod(

'greet',

{

accepts: {arg: 'msg', type: 'string'},

returns: {arg: 'greeting', type: 'string'}

}

);

};


What does that cb mean? How can we know it accepts two parameters, null and a string? Hope someone could help.

Answer

So you have an Async function Person.greet which you'll call like this:

Person.greet('hello', function(err){
    ...
});

Notice that after 'hello' a second argument was passed and it is actually a function. It can also be defined outside with a name and passed this way:

function callback(err){
    ...
}
Person.greet('hello', callback);

Now it looks exactly how the Person.greet was defined:

Person.greet = function(msg, cb) {
  cb(null, 'Greetings... ' + msg);
}

The difference here is just that in the definition it uses a different name: cb. It could've used any name since to it cb is just an argument. But generally "cb", "done", or "next" are used as a standard practice.

Comments