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 AJAX calls can be made asynchronous or non-blocking (using callbacks)... Is this true of Node.js as well, or are all Node.js callback functions made asynchronous/non-blocking?

Answers:

Answer

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).

Answer

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.

Answer

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

function foo(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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.