Skip to content Skip to sidebar Skip to footer

Are All Node.js Callback Functions Asynchronous?

I'm working on learning Node.js and all I hear in every tutorial is 'Node is asynchronous and no -blocking!' I've heard in regular browser JavaScript only certain things such as AJ

Solution 1:

are all Node.js callback functions made asynchronous/non-blocking?

No. Only I/O is usually asynchronous, but many other callbacks are synchronous. Always check the docs.

Examples of async functions:

  • Async Filesystem access (they have sync counterparts without callbacks, though)
  • Timers (setTimeout)
  • process.nextTick, setImmediate
  • most database connections
  • network connections
  • Promises

Examples of sync callbacks:

See also Are all javascript callbacks asynchronous? If not, how do I know which are? (including some other examples).

Solution 2:

When you pass a callback to a function, you expect that function to call your callback function some other time. However, it isn't automatically asynchronous.

Suppose I have this code:

function callSomething(callback) {
  callback();
}

function theCallback() {
  // Do something time consuming here
}

callSomething(theCallback);

In this case, we're passing a callback, but the callback gets called immediately on the existing call stack. This is considered bad practice and is strongly discouraged in Node.js. If you want to call a callback fairly immediately, use process.nextTick():

function callSomething(callback) {
  process.nextTick(callback);
}

So the direct answer to your question is mostly yes. When you specify a callback to functions in Node.js, by convention they will be called on another callstack at a later point in time. But if you are using some bad code from someone who didn't know how to follow this convention, there is no guarantee.

Solution 3:

Nope, they are not automatically asynchronous. Consider this code:

functionfoo(array, filter, callback) {
    var result = []
    for (var i = 0; i < array.length; i++) {
        if (filter(array[i])) result.push(array[i]);
    }

    callback(result);
}

And now imagine a program like this:

foo([ 1, 2, 3, 4 ], function() { while(true); }, console.log);
console.log('Blocking?');

If foo would be asynchronous then Blocking? would immediatly appear, but it does not!


You can be pretty sure, however, that most / all of the standard library taking a callback is non-blocking async code. Most of it also has a Sync counterpart.

Post a Comment for "Are All Node.js Callback Functions Asynchronous?"