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?
A callback is a function called at the completion of a given task; this prevents any blocking, and allows other code to be run in the meantime. The Node.js way to deal with the above would look a bit more like this: function processData (callback) { fetchData(function (err, data) { if (err) { console.
So from my findings i assure you ES6 promises are faster and recommended than old callbacks.
Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.
For example: In Node. js, when a function start reading file, it returns the control to execution environment immediately so that the next instruction can be executed. Once file I/O gets completed, callback function will get called to avoid blocking or wait for File I/O.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With