Are all Node.js callback functions asynchronous?
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:
- EventEmitter (depends on when the event is fired)
-
Array iteration methods like
forEach
-
Array
sort
comparator callbacks -
String
replace
match callbacks
See also Are all javascript callbacks asynchronous? If not, how do I know which are? (including some other examples).
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.
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.