简体   繁体   中英

nodeJS Async vs Sync

In nodeJS it is a general practice and recommendation to use async methods and make callbacks to the next function.

I set up a nodeJS using expressJS for testing purposes and I wrote sync and async methods. Both methods work and express will answer to all requests without any perceptible delay whether using async or sync methods.

Although I use async methods in my project, the articles I read that encourage to use async methods did not explain why in deep. Sync methods would avoid a callback hell .

So I got curious, why not use sync methods since they both work? Would it impact in response time/performance by using one or another?

Node runs on a single thread. If you are handling lots of connections, there will be surely more IO-bound tasks than CPU-bound tasks. For example, DB calls. While you are waiting for a database query result, you can receive more requests, or do other jobs.

The problem starts when you need to do something that is CPU-bound: a task that may take much time. You need to split the task, making a tiny part of it, and then scheduling the rest to a later time until it's finished, or you can delegate it to another server / process, whatever.

If you decide to go sync, the server won't handle any more requests while doing that job. Yes, you will avoid the callback hell, but at the cost of doing one task from start to the end no matter how long it is. If you are trying to handle lots of connections, this won't be good.

A good example of when it is a trouble, are the for loops:

for (let x of ['some', 'huge', 'array']) {
  // Do something heavy here, until it's not finished, server won't do
  // anything more than this heavy task
}

While "doing something", the server application won't handle any other incoming request. Of course, the problem will be serious when you have a heavier task, and lots of requests.

In a serious Node server, you don't want a synchronous loop, unless it performs better than an asynchronous solution because of X motive. So, you go async with setTimeout, setImmediate, process.nextTick, Promises, etc. And, probably the first approach you take is going with the continuation-passing style, it means, passing callbacks to be executed after the work is done, and probably you will hit the callbacks hell wall.

That's the moment when you go with Promises, or generators, or both: https://davidwalsh.name/async-generators

This way, you will avoid the callbacks hell, and also get a nicer code (subjective). Also you maybe want to keep an eye on async/await: https://github.com/tc39/ecmascript-asyncawait .

You don't have any notable advantage because you are the only user making requests. Make tests with, say, thousands of connections.

Abrazo.

Well...

You can put food in the microwave, take a bath in the meantime, and when you finish your bath you can (probably) you take your food out of the microwave and eat it. If the food isn't ready yet, you can do something else until it's ready. That's the async way.

Or, your can put food in the microwave, stare at the microwave until it finishes, eat your food, and then take your bath. That's the sync way.

Considering the code bellow:

server.get('/wait', function(request, response){

    var wait = true;
    while (wait) { // force synchronous delay of 10s
        setTimeout(function() {
            console.log('answering now');
            response.send('<pre>hello, i am 10s late</pre>');
            wait = false;
        }, 10000);
    }
});

server.get('/now', function(request, response){

    response.send('<pre>hello!</pre>');
});

Calling first http://127.0.0.1/wait and then http://127.0.0.1/now :

/now is answered right away. One thread does not interfere in one another.


Calling first http://127.0.0.1/wait and then http://127.0.0.1/wait :

The second call won't be answered before the 1st call have been answered. One thread does interfere in one another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM