Search code examples
node.jsblocking

Is the following node.js code blocking or non-blocking?


I have the node.js code running on a server and would like to know if it is blocking or not. It is kind of similar to this:

function addUserIfNoneExists(name, callback) {
    userAccounts.findOne({name:name}, function(err, obj) {
        if (obj) {
            callback('user exists');
        } else {

            // Add the user 'name' to DB and run the callback when done.
            // This is non-blocking to here.
            user = addUser(name, callback)

            // Do something heavy, doesn't matter when this completes.
            // Is this part blocking?
            doSomeHeavyWork(user);
        }
    });
};

Once addUser completes the doSomeHeavyWork function is run and eventually places something back into the database. It does not matter how long this function takes, but it should not block other events on the server.

With that, is it possible to test if node.js code ends up blocking or not?


Solution

  • Generally, if it reaches out to another service, like a database or a webservice, then it is non-blocking and you'll need to have some sort of callback. However, any function will block until something (even if nothing) is returned...

    If the doSomeHeavyWork function is non-blocking, then it's likely that whatever library you're using will allow for some sort of callback. So you could write the function to accept a callback like so:

    var doSomHeavyWork = function(user, callback) {
      callTheNonBlockingStuff(function(error, whatever) { // Whatever that is it likely takes a callback which returns an error (in case something bad happened) and possible a "whatever" which is what you're looking to get or something.
        if (error) {
          console.log('There was an error!!!!');
          console.log(error);
          callback(error, null); //Call callback with error
        }
        callback(null, whatever); //Call callback with object you're hoping to get back.
      });
      return; //This line will most likely run before the callback gets called which makes it a non-blocking (asynchronous) function. Which is why you need the callback.
    };