Why do some synchronous libraries in nodejs use a callback?

I am a new nodejs developer and I think I understand nodejs projects.

I understand that some libraries related to syscall must be asynchronous. These jobs will be queued and processed in different thread pools and will be notified via a callback when they are completed.

However, I cannot understand why some non-syscall libraries use callbacks as a communication method. For example, the xml2js library is written in Javascript, and there seems to be no reason for this parsing function to return status via a callback. It can directly return the result of processing, and the readability of the code will be increased.

My question is, is there some reason some nodejs library developers stick with callback-based communication instead of just using the return value?

+5
source share
4 answers

There is nothing wrong with the callback style.

var return = doSomething();
...

doSomething(function(return) {
    ...
});

This is preference. They are both valid. The first one just seems “better” because you are used to it.

One good reason for the latter is that the API does not need to be changed when you change your library to non-blocking.

, node - -. - js2xml, , , node 0,6, API- - -, .

, API ( , ).

+5

, .

, , , , , .

+3

LibXML. , IO System-Level IO ?

, XML DTD . XInclude, XML-Parsers.

, API, - , , , IO.

, , XML-Parser -, XInclude DTD/Schema. "" , XInclude Processing Schema validation API.

So often, if you are writing an API, you better start the asynchronous / callback from the very beginning, because you never know what you want to do later.

+1
source

Callbacks can be useful in various scenarios, for example, when you iterate through some collection (which is encapsulated for some reason):

function Foo() {
    this._data = [1, 2, 3, 4, 5]; 
}

Foo.prototype.forEach = function(callback) {
    var i, 
        len = this._data.length;

    for(i = 0; i < len; i++) {
        callback("Item number: " + this._data[i]);
    }
}

var foo = new Foo();

foo.forEach(function(item) {
    console.log(item);
});
0
source

All Articles