当调用'/ a'时,'/ b'可以立即执行。但如果我调用另一个'/ a',第二个等待第一个结束。如何让'/ a'真正异步调用?
代码:
app.get '/a', (req, res, next) ->
f = ->
res.send 'a'
console.log 'end', new Date()
console.log 'sleep', new Date()
setTimeout f, 10000
app.get '/b', (req, res, next) ->
res.send 'b'
输出:
Express server listening on port 3000 in development mode
sleep Sun Oct 14 2012 12:37:52 GMT+0800 (SGT)
GET /b 200 9ms - 1
end Sun Oct 14 2012 12:38:02 GMT+0800 (SGT)
GET /a 200 10022ms - 1
sleep Sun Oct 14 2012 12:38:02 GMT+0800 (SGT)
end Sun Oct 14 2012 12:38:12 GMT+0800 (SGT)
GET /a 200 10005ms - 1
答案 0 :(得分:1)
我明白了,因为我在同一个浏览器上运行了两个'/ a'。我只是尝试在chrome中运行一个,而在firefox中运行另一个,它们是异步处理的。看起来很有趣。
答案 1 :(得分:0)
我不确定你在看什么。当我运行测试时,我得到了预期的结果 - 对\a
的请求是异步处理的。如果您尝试使用以下代码并使用DEBUG=* node app.js
执行它,您会得到与我相同的结果吗?
var express = require('express'),
app = express();
app.get('/a', function (req, res, next) {
var f = function () {
res.send('a');
console.log('end', new Date());
};
console.log('sleep', new Date());
setTimeout(f, 10000);
});
app.get('/b', function (req, res, next) {
res.send('b');
});
app.listen(4000);
以下是在前两个请求正在休眠时向\a
运行两个请求和向\b
发送请求的输出。
express:router dispatching GET /a (/a) +52s // first call to \a
express:router matched get /a +1ms
sleep Sat Oct 13 2012 21:59:42 GMT-0700 (PDT)
connect:dispatcher query +530ms
connect:dispatcher expressInit +1ms
connect:dispatcher router +0ms
express:router dispatching GET /a (/a) +530ms // second call to \a in parallel
express:router matched get /a +0ms
sleep Sat Oct 13 2012 21:59:42 GMT-0700 (PDT)
connect:dispatcher query +874ms
connect:dispatcher expressInit +0ms
connect:dispatcher router +0ms
express:router dispatching GET /b (/b) +874ms // call to \b handled immediately
express:router matched get /b +0ms
end Sat Oct 13 2012 21:59:52 GMT-0700 (PDT) // first call to \a ends
end Sat Oct 13 2012 21:59:52 GMT-0700 (PDT) // second call ends at same time
您可以看到对\b
的请求立即结束,然后对\a
的两个请求都在10秒后完成,这意味着它们实际上是并行处理的(如预期的那样)。
答案 2 :(得分:0)
比尔,我的代码得到了不同的结果。我通过浏览器运行这些。我在Linux上使用Express 3只有一个核心。
express:application booting in development mode +0ms
connect:dispatcher use / query +0ms
connect:dispatcher use / expressInit +0ms
connect:dispatcher use / router +2ms
express:router defined get /a +0ms
express:router defined get /b +1ms
connect:dispatcher query +12s
connect:dispatcher expressInit +2ms
connect:dispatcher router +0ms
express:router dispatching GET /a (/a) +12s
express:router matched get /a +0ms
sleep Sun Oct 14 2012 13:20:37 GMT+0800 (SGT)
connect:dispatcher query +3s
connect:dispatcher expressInit +0ms
connect:dispatcher router +0ms
express:router dispatching GET /b (/b) +3s
express:router matched get /b +1ms
end Sun Oct 14 2012 13:20:47 GMT+0800 (SGT)
connect:dispatcher query +6s
connect:dispatcher expressInit +0ms
connect:dispatcher router +0ms
express:router dispatching GET /a (/a) +6s
express:router matched get /a +0ms
sleep Sun Oct 14 2012 13:20:47 GMT+0800 (SGT)
end Sun Oct 14 2012 13:20:57 GMT+0800 (SGT)