node.js - attaching event handlers on time

前端 未结 2 587
独厮守ぢ
独厮守ぢ 2021-01-12 16:05

I\'m studying node.js and came across this example in the node.js manual:

...
var req = http.request(options);
req.end();

req.on(\'upgrade\', function(res,          


        
2条回答
  •  醉话见心
    2021-01-12 16:56

    The key thing to understand is that there is only a single event loop and control ONLY leaves the current "tick" of the event loop when you call an asynchronous function. Usually this happens naturally when you do I/O (every few lines of code is common) or call setTimeout/setInterval (fairly rare). So as long as all of your event handlers are registered within the same tick of the event loop, you will never loose any data. Moreover, within that tick of the event loop, it doesn't matter what order you attach your handlers, because during that tick your code is literally the only thing node is executing, so no other code can receive I/O or invoke any event handlers until the current event loop tick completes. It's not about waiting "long enough" or network latency or anything like that. It's the simplicity of a single event loop that guarantees predictable operation with regard to the event handler functions.

提交回复
热议问题