Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many callbacks issue

I know that writing async functions is recommended in nodejs. However, I feel it's not so nescessary to write some non IO events asynchronously. My code can get less convenient. For example:

//sync
function now(){
    return new Date().getTime();
}
console.log(now());

//async
function now(callback){
    callback(new Date().getTime());
}
now(function(time){
    console.log(time);
});

Does sync method block CPU in this case? Is this remarkable enough that I should use async instead?

like image 931
user3925697 Avatar asked Aug 16 '14 16:08

user3925697


1 Answers

Async style is necessary if the method being called can block for a long time waiting for IO. As the node.js event loop is single-threaded you want to yield to the event loop during an IO. If you didn't do this there could be only one IO outstanding at each point in time. That would lead to total non-scalability.

Using callbacks for CPU work accomplishes nothing. It does not unblock the event loop. In fact, for CPU work it is not possible to unblock the event loop. The CPU must be occupied for a certain amount of time and that is unavoidable. (Disregarding things like web workers here).

Callbacks are nothing good. You use them when you have to. They are a necessary consequence of the node.js event loop IO model.

That said, if you later plan on introducing IO into now you might eagerly use a callback style even if not strictly necessary. Changing from synchronous calls to callback-based calls later can be time-consuming because the callback style is viral.

like image 178
usr Avatar answered Sep 30 '22 17:09

usr