简体   繁体   English

Node JS 中的事件循环阻塞和异步编程

[英]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.我是 Node js 编程的新手,因此想非常恰当地理解核心概念和实践。 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. AFAIK 节点 js 具有非阻塞 I/O,允许所有磁盘和其他 I/O 操作以异步方式运行,而其 JS 运行在使用事件循环管理资源和执行路径的单线程中。 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.我相信控制台消息将首先打印,然后执行processData函数代码,然后调用回调函数。 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. JavaScript(几乎和任何其他语言一样)按顺序运行。 If you write如果你写

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

you expect the result to be 3 , not 4 .您希望结果是3 ,而不是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 .预期的执行顺序是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() .有许多使用回调模式的同步函数,例如Array.prototype.forEach()

What really happens is that NodeJS has this event loop under the hood.真正发生的是 NodeJS 在幕后有这个事件循环。 You can tell it to schedule something and run later by calling multiple special functions: setTimeout , setInterval , process.nextTick to name few.您可以通过调用多个特殊函数告诉它安排一些事情并稍后运行: setTimeoutsetIntervalprocess.nextTick等等。 All I/O also schedules some things to be done on the event loop.所有 I/O 还安排了一些要在事件循环上完成的事情。 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).预期的执行顺序是这个bar -> (schedule callback) -> foo然后callback将在某个时刻触发(即当所有其他排队的任务被处理时)。

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.您应该尝试在您的函数中使用计时器、api 来感受节点 js 非阻塞异步模式。 I hope The Node.js Event Loop will help you to get started.我希望Node.js 事件循环能帮助你入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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