Express使用setTimeout序列化调用?

时间:2016-02-22 14:59:27

标签: node.js express

我有以下示例(摘自官方明文):

var express = require('express');
var app = express();

app.get('/', function(req, res){
    console.log('request: ' + (new Date()))

    setTimeout(function() {
        console.log('response: ' + (new Date()))
        res.send('hello world');
    }, 5000);
});

app.listen(3000);

现在,当我在3个标签页中打开http://localhost:3000/并同时重新加载所有标签时,我会收到此日志:

request: Mon Feb 22 2016 15:52:15
response: Mon Feb 22 2016 15:52:20
request: Mon Feb 22 2016 15:52:20
response: Mon Feb 22 2016 15:52:25
request: Mon Feb 22 2016 15:52:25
response: Mon Feb 22 2016 15:52:30

所以基本上表达是按顺序一次一个地处理请求。这不是我的预期。它为什么这样做?任何人都可以确认这只是一个Windows问题,因为我在这里坐在Windows上?

此外setTimeout似乎不是问题,因为当我遗漏所有快递时,一切都很好:

console.log('request: ' + (new Date()))
setTimeout(function() {
    console.log('response: ' + (new Date()))
}, 5000);

console.log('request: ' + (new Date()))
setTimeout(function() {
    console.log('response: ' + (new Date()))
}, 5000);

console.log('request: ' + (new Date()))
setTimeout(function() {
    console.log('response: ' + (new Date()))
}, 5000);

生成我期望的日志:

request: Mon Feb 22 2016 15:56:57
request: Mon Feb 22 2016 15:56:57
request: Mon Feb 22 2016 15:56:57
response: Mon Feb 22 2016 15:57:02
response: Mon Feb 22 2016 15:57:02
response: Mon Feb 22 2016 15:57:02

我错过了什么?提前谢谢!

编辑:节点4.2.6,表达4.13.4

1 个答案:

答案 0 :(得分:2)

问题出在您的浏览器上吗?我无法重现。我像使用express@4.13.4一样安装它,并运行此命令:

curl http://localhost:3000/ & curl http://localhost:3000/ & curl http://localhost:3000/ &

我收到了这个日志:

request: Mon Feb 22 2016 16:01:15 GMT+0100 (CET)
request: Mon Feb 22 2016 16:01:15 GMT+0100 (CET)
request: Mon Feb 22 2016 16:01:15 GMT+0100 (CET)
response: Mon Feb 22 2016 16:01:20 GMT+0100 (CET)
response: Mon Feb 22 2016 16:01:20 GMT+0100 (CET)
response: Mon Feb 22 2016 16:01:20 GMT+0100 (CET)