简体   繁体   English

Node.JS-使用异步功能处理传入的请求

[英]Node.JS - Handling incoming requests with Async functions

As far as I understand Node.js is single threaded and handles each request one at a time. 据我了解,Node.js是单线程的,并且一次处理每个请求。 However, when making asynchronous calls it should be able to deal with new requests while the callbacks haven't been called yet. 但是,在进行异步调用时,它应该能够处理新的请求,而尚未调用回调。

So when I make 3 request simultaneously to the following server implementation, why does it wait for 10 sec for the first response, and then 20 for the 2nd, and 30 for the 3rd...? 因此,当我同时向以下服务器实现发出3个请求时,为什么它对第一个响应等待10秒,然后对第二个响应等待20秒,对第三个响应等待30秒...?

var express = require('express');    
    var app = express();
    app.get('*', function(req, res) {
        setTimeout(function(){
            res.end('done')
        },10000)
    });
    app.listen(8000);

Instead of checking this using your browser, you should test it with another node.js script... For example, using this script: 与其使用浏览器进行检查,不如使用另一个node.js脚本进行测试...例如,使用以下脚本:

var http = require('http');

function test(timestamp) {
    http.get('http://127.0.0.1:8000',function(res) {
           console.log(new Date() - timestamp);
    });
}


for (var i = 0 ; i < 5 ; i++) {
    test(new Date().getTime());
}

I get the following result (Using your code as http server): 我得到以下结果(将您的代码用作http服务器):

> node test.js
10032
10029
10029
10029
10030

So it seems that the problem wasn't on you're node.js code. 看来问题不在于您是node.js代码。

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

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