Maciej Kravchyk
Maciej Kravchyk

Reputation: 16607

Node.js asynchronous function, process.nextTick()

I'm writing a node backend and I'm a little confused how should I deal with async functions. I've read about process.nextTick(), but how often should I use. Most of my code is based on callbacks, like database calls, which are asynchronous by themselves. But I also have a few functions of my own, that should be async.

So which one is a good example of async function?

function validateUser1(user, callback) {

  process.nextTick(function() {    

     //validate user, some regex and stuff

     callback(err, user);

  });

}

function validateUser2(user, callback) {

  //validate user, some regex and stuff

  process.nextTick(callback, err, user);

}

function validateUser3(user, callback) {

  process.nextTick(function() {    

    //validate user, some regex and stuff

    process.nextTick(callback, err, user);

  });

}

I don't know whether I should wrap everything in process.nextTick , or wrap just the callback? or both?

And overall, the idea with node.js is to write lots of small functions rather than bigger ones, and call them asynchronously to not block other events, right?

Upvotes: 0

Views: 3306

Answers (3)

Valdi
Valdi

Reputation: 39

I still confused with the answer provided. I watched short course on Lynda.com about NodeJS (Advanced NodeJS). The guy provides the following example of using process.nextTick()

function hideString(str, done) {
    process.nextTick(()=> {
        done(str.replace(/[a-zA-Z]/g, 'X'))
    })

}

hideString("Hello World", (hidden) => {
    console.log( hidden );
});

console.log('end')

If you do not use, console.log('end') will be printed first. not async. I understood it as to write async code, you will need process.nextTick. Than it is not clear how async code is written in JS on frontend without process.next Tick()

Upvotes: 0

user5733510
user5733510

Reputation:

process.nextTick() will execute your callback before continuing with the event loop. This will block your thread and can stop incoming connections from being handled if the callback you passed to process.nextTick() is something CPU expensive like encrypting, calculating PI etc.

From what I understand you try to make your functions asynchronous by passing them to process.nextTick(). That is not how it works. When you pass something to process.nextTick() it will execute before the eventloop is executed the next time. This will not make your function non-blocking, as the function you execute is still running in the main thread. Only I/O Operations can be non-blocking.

Therefore it is irrelevant if you wrap your CPU-intensive functions with process.nextTick() or just execute them right away.

If you want to read more background information, here is the resource: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick

Upvotes: 1

pid
pid

Reputation: 11607

If you have just CPU code (no I/O) you should try and go as far along as you can. Avoid async and tiny functions which fragment your code unnecessarily.

Take the opportunity and write clean, readable, linear code whenever possible. Only revert to async when absolutely necessary, such as stream I/O (file or network).

Consider this. Even if you have 1000+ lines of JS code, it will still be executed blazingly fast. You really do not need to fragment it (unless proven to be too cumbersome, such as very deep loops, but you have to measure it first)!

If you don't test the linear code first and actually SEE that you need to fragment it, you'll end up with premature optimization, which is a bad thing for maintainability.

I'd really go straight away with this:

function validateUser1(user, callback) {
   //validate user, some regex and stuff
   callback(err, user);
}

And if possible, remove the function altogether (but this is a matter of how you write the rest of the code).

Also, don't use nextTick() if you don't really need it. I've implemented a cloud server with many TCP/IP sockets, database connections, logging, file reading and a lot of I/O, but NOT ONCE did I use nextTick() and it runs really smooth.

Upvotes: 3

Related Questions