node.js - attaching event handlers on time

前端 未结 2 559
独厮守ぢ
独厮守ぢ 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:31

    What you miss is that JavaScript isn't asynchronous at all! What I mean is that JavaScript is single-threaded and asynchronous operations are actually not asynochronous. There is a very fancy queue model which gives as the illusion of JavaScript being asynchronous (don't get me wrong: it still is the most efficient model).

    So what does it mean? It means that once the synchronous code is running it is impossible for other code to be running parallely. So for example in this code

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

    the request is scheduled, but the main thread (i.e. the operation) hasn't ended at req.end(). As long as the main operation has not finished no asynchronous code can fire in-between. In particular the handler is always set before the actual event has any chance to occure.

    One more example to make it a bit clearer. Consider this code:

    var http = require('http');
    http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World\n');
        while(true) { } // <------ infinite loop doing nothing
    }).listen(1337, '127.0.0.1');
    

    Note that the first request will finish with success. But any other request will never get a response. This is because the loop will never finish the operation and JavaScript cannot jump to another event because of it. This code permamently crashes the app beyond any hope. So be careful with synchronous code with Node.js. :)

提交回复
热议问题