Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic successful callback in Node.js

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?

like image 905
Ivan Krechetov Avatar asked Mar 26 '14 10:03

Ivan Krechetov


People also ask

What are callbacks in node JS?

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.

What is faster callback or promise in Nodejs?

So from my findings i assure you ES6 promises are faster and recommended than old callbacks.

What is used to handle callbacks in Nodejs?

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.

How do you write a callback function in node JS?

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.


1 Answers

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.

like image 181
Louis Avatar answered Sep 27 '22 02:09

Louis