I’m a new nodejs developer, and I think that I understand designs of nodejs.
I can understand that some syscall-related library should be asynchronous. These job will be queued and processed in different thread pool, and notified via callback when it finished.
However, I can’t understand why some non-syscall related libraries are using callback as a communication method. For example, xml2js library is written in Javascript, and apparently, there is no reason that this parse function will return status via callback. It can return processing result directly, and code readability will be increased.
My question is, is there any reason that some nodejs library designers are sticking to callback-based communication instead of just using return value?
There is nothing wrong with the callback style.
This is preference. They’re both valid. The former only seems “better” because you’re used to it.
One good reason for the latter is that the API doesn’t have to change when you change your library to be non-blocking.
People need to be reminded that node is a low level non blocking IO library. If you’re going to do something like js2xml then clearly you’re waiting for node 0.6 to standardise the web worker sub process API so you can send the heavy lifting to a sub proccess and do the actual hard work in a non blocking fashion.
To do this in a non blocking manner your API needs to be asynchronous (or you need it build into the language).