philip yoo
philip yoo

Reputation: 2522

Using caolan's async library, when should I use process.nextTick and when should I just invoke the callback?

I've been reading up on the differences, and it's hard to think about it when utilizing a library that helps with async methods.

I'm using https://github.com/caolan/async to write specific async calls. I'm having a hard time understanding the use of process.nextTick within some of these async methods, particularly async series methods, where async methods are basically performed synchronously.

So for example:

async.waterfall([
    next => someAsyncMethod(next),
    (res, next) => {
        if (res === someCondition) {
            return anotherAsyncMethod(next);
        }
        return process.nextTick(next); // vs just calling next()
    },
], cb);

I've seen this done in code before. But I have no idea why? Just invoking next instead of process.nextTick gives me the same results?

Is there any reason for using process.nextTick in these scenarios, where there is an async method being controlled in a synchronous manner?

Also, what about in an async like the following?

async.map(someArray, (item, next) => {
    if (item === someCondition) {
        return anotherAsyncMethod(next);
    }
    return process.nextTick(next); // vs just calling next()
}, cb);

Thanks!

Upvotes: 0

Views: 107

Answers (1)

Brenn
Brenn

Reputation: 1384

The code is happening in a SEQUENTIAL manner, not a synchronous manner. It's an important difference.

In your code, the async methods are called one after another, in sequence. HOWEVER, while that code is executing, node.js can still respond to other incoming requests because your code yields control.

Node is single-threaded. So if your code is doing something synchronously, node cannot accept new requests or perform actions until that code is finished. For instance, if you did a synchronous web request, node would stop doing ANYTHING ELSE until that request was finished.

What's really happening is this:

  1. Start async action in background (yield control)

  2. Node is available to handle other stuff

  3. Async action 1 completes. Node starts async action 2 and yields control.

  4. Node can accept other requests/handle other stuff.
  5. Async action 2 completes...

And so on. Process.nextTick() says to node 'Stop dealing with this for a while, and come back once you've handled the other stuff that's waiting on you'. Node goes off and handles whatever that is, then gets back to handling your scheduled request.

In your case, there is nothing else waiting so node just continues where it left off. However, if there WERE other things going on like other incoming HTTP requests, this would not be the case.

Feel free to ask questions.

Upvotes: 1

Related Questions