Reputation: 251
I'm looking at a Node.js code sample that uses "if (err) {//code//);" statements to control the output of its functions - but when the functions are called I don't see anything being passed to them, its as if the "err" parameter is defined by invisible code behind the scenes...
The below code is asynchronous and uses an external module from an SDK, should that be of note.
/* "client.sendEvent" sends the data contained within the variable "message"
to its destination, when this is complete the callback function "printResultFor"
is called and a string is passed to that */
client.sendEvent(message, printResultFor('Message'));
//printResultFor looks like this:
var printResultFor = function (op) {
return function printResult(err, res) {
if (err) console.log(op + ' error: ' + err.toString());
if (res) {
console.log(op + ' status: ' + res.constructor.name);
};
};
}
My questions are:
and
I did wonder if the answer lies in the external module but I don't know...
(Final Note: I'm a self-taught novice with Javascript and Node, I bet this is trivial to most people but thank you for any explanations and help you can offer.)
Upvotes: 2
Views: 2777
Reputation: 1446
err
as the first parameter in a callback. When there is no error, it is typically the value null
. The res
is the data you get when a error is not encountered.Upvotes: 2
Reputation: 115498
The printResultFor
is called, and it returns the defined function inside. Whatever called the printResultFor
then calls the internal function which it now has access to, because it was returned. It just happens in code where you aren't looking for it.
for example:
var printResult = printResultFor(something);
printResult(null, dataObjectHere);
By doing this, the printResult
has access to the op
variable through closure (since it was defined in the printResultFor
function, it has access to all the variables and parameters defined in it.)
Upvotes: 2
Reputation: 5742
This is called Error first callback and it's not a language feature but a convention instead.
As Fred K. Schott says in The Node.js Way - Understanding Error-First Callbacks:
The first argument of the callback is reserved for an error object. If an error occurred, it will be returned by the first err argument.
The second argument of the callback is reserved for any successful response data. If no error occurred, err will be set to null and any successful data will be returned in the second argument.
Basically what it says is that if there is any error you'll know by checking the first parameter.
This is the expected behaviour for any callback based nodejs library and you should design your interfaces alike.
Upvotes: 7