Reputation: 19220
By convention in Node, an asynchronous callback accepts an error as its first argument. In case of success, the first argument must not be present. I personally used to write
callback(undefined, result);
in that case. However, I see in other people's code
callback(null, result);
prevailing. Is it "officially" documented anywhere? Which of the two options is idiomatic Node? Are there any significant reasons to prefer one over another?
Upvotes: 7
Views: 2109
Reputation: 12265
In case of errors, undefined
and null
are always considered the same.
You can use both of them. People use null only because it's shorter.
If you're checking for errors, you can check for both null and undefined in one statement using if (err == null) { ... }
approach.
Upvotes: 0
Reputation: 151401
If we interpret "idiomatic Node" as "what Node itself does", then null
would be what is idiomatic. If you type this at the Node prompt (on a *nix machine), you'll get true
:
require("fs").readFile("/dev/null", function (err) { console.log(err === null) })
I've tried with other callbacks from the fs
module and got the same behavior. I've not tested all places in Node's API where callbacks are used.
I've not found a reference that states that Node must set err
to null
in such cases.
Upvotes: 9
Reputation: 1282
If you are concerned whether to use null vs undefined, then go with null. Strictly speaking in JavaScript undefined
is considered to be abnormal.
You can read more on this at What is the difference between null and undefined in JavaScript?.
There is also a nice post about Node.js callback conventions - http://blog.gvm-it.eu/post/22040726249/callback-conventions-in-node-js-how-and-why.
Upvotes: 3