Node.js is stated to be asynchronous, event-driven, non-blocking I/O, but how can I identify if my script is asynchronous? Or non-blocking?
There is a list of functions which are asynchronous, including:
process.nextTick( ... )
setTimeout( ... )
setInterval( ... )
From File System module:
var fs = require( 'fs' );
fs.rename( ... )
fs.stat( ... )
fs.readFile( ... )
fs.writeFile( ... )
fs...
many more for fs, basically asynchronous have their synchronous versions with "Sync" suffix at the end ( synchronous versions should be avoided though ).
There are many many more examples. EventEmitters can be considered asynchronous ( for example HTTP servers or streams ), although technically they aren't ( they depend on asynchronous operations ).
Basically almost everything which accepts callback as a parameter is asynchronous ( or depends on asynchronous operation ), for example:
process.nextTick( function( ) { // <--- the callback
console.log( 'nextTick' );
});
console.log( 'test' ); // <--- will fire before the callback, i.e. asynchronouos
Keep in mind that this is obviously not a rule, notable example:
var arr = [ 1, 2, 3 ];
arr.forEach( function(el) { // <--- the callback
console.log( el );
});
console.log( 'test' ); // <--- will fire after the callback, i.e. synchronous
So synchronous code is a code which fires line after a line and order of lines matters. The asynchronous code is the opposite: the order of lines ( almost ) does not matter. In the example with process.nextTick you can change the order of process.nextTick and console.log('test') and the result will still be the same.
Read the documentation and try to memorize all basic asynchronous functions.
And one more advice: the best way to learn is learn by doing. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With