简体   繁体   中英

Event loop blocking and async programming in Node JS

I am newbie to Node js programming and hence want to understand the core concepts and practises very appropriately. AFAIK node js has non-blocking I/O allowing all disk and other I/O operations running async way while its JS runs in single thread managing the resource and execution paths using Event Loop. As suggested at many places developers are advised to write custom functions/methods using callback pattern eg

function processData(inputData, cb){
   // do some computation and other stuff

   if (err) {
    cb(err, null);
   }else{
    cb(null, result);
  }
}
callback  =  function(err, result){

 // check error and handle

 // if not error then grab result and do some stuff 
}

processData(someData, callback)
// checking whether execution is async or not
console.log('control reached at the end of block');

If I run this code everything runs synchronously printing console message at last. What I believed was that the console message will print first of all followed by execution of processData function code which will in turn invoke the callback function. And if it happens this way, the event loop will be unblocked and would only execute the response to a request when the final response is made ready by 'callback' function.

My question is:- Is the execution sequence alright as per node's nature Or Am I doing something wrong Or missing an important concept?

Any help would be appreciate from you guys !!!

JavaScript (just as pretty much any other language) runs sequentially. If you write

var x = 1;
x *= 2;
x += 1;

you expect the result to be 3 , not 4 . That would be pretty bad. The same goes with functions. When you write

foo();
bar();

you expect them to run in the very same order. This doesn't change when you nest functions:

var foo = function() {};
var bar = function(clb) {
    clb();
    foo();
};
var callback = function() {
};
bar(callback);

The expected execution sequence is bar -> callback -> foo .

So the biggest damage people do on the internet is that they put equals sign between asynchronous programming and callback pattern. This is wrong . There are many synchronous functions using callback pattern, eg Array.prototype.forEach() .

What really happens is that NodeJS has this event loop under the hood. You can tell it to schedule something and run later by calling multiple special functions: setTimeout , setInterval , process.nextTick to name few. All I/O also schedules some things to be done on the event loop. Now if you do

var foo = function() {};
var bar = function(clb) {
    procress.nextTick(clb);  // <-- async here
    foo();
};
var callback = function() {
};
bar(callback);

The expected execution sequence is this bar -> (schedule callback) -> foo and then callback will fire at some point (ie when all other queued tasks are processed).

That's pretty much how it works.

You are writing synchronous code all the way down and expecting it to run asynchronously. Just because you are using callbacks does not mean it's an asynchronous operation. You should try using timers, api within your functions to feel node js non blocking asynchronous pattern. I hope The Node.js Event Loop will help you to get started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM