2016-03-08 30 views
1

我目前在玩Koa 2,具有异步/等待功能。假设我有两条路线,都在数据库上查询。一个查询是一个简单的问题。在这里,第二个是我做过什么:async/await w/koa 2&mongoose

q.$where = `function() { 
    var d = new Date((new Date()).getTime() + 2000); 
    while (d > (new Date())) { }; return true;}` 
return await this.findOne(q) 

$where增加了延迟2秒钟来模拟一个缓慢的查询。如果我要求两次这条路线(慢的)这样的:

$.get('/api/users/slug') 
$.get('/api/users/slug') 

服务器日志:

<-- GET /api/users/slug 
--> GET /api/users/slug 200 2,004ms 183b // after 2sec 
<-- GET /api/users/slug 
--> GET /api/users/slug 200 2,003ms 183b // after 4sec 

我们看到了第二个请求2秒后命中服务器。
而如果我要求:

$.get('/api/users/slug') 
$.get('/api/other/route') 

另一条路线是做同样的事情,但没有延迟,服务器说:

<-- GET /api/users/hugo 
<-- GET /api/other/route 
--> GET /api/other/route 200 3ms 183b 
--> GET /api/users/hugo 200 2,004ms 183b 

我们看到了第二个请求到达服务器后右第一。

我竟然指望第一次测试给我

<-- GET /api/users/slug 
<-- GET /api/users/slug 
--> GET /api/users/slug 200 2,004ms 183b 
--> GET /api/users/slug 200 2,003ms 183b 

所以整个事情本来需要2秒,而不是4.你知道为什么不?

这是一个相当长的问题,我试图给你所有的相关信息。谢谢!

+0

使用'await new Promise(resolve => setTimeout(resolve,2000))来模拟延迟不会更容易吗? – Bergi

+0

是的!我想模拟一个缓慢的mongodb请求,而不需要链接JS代码,但结果会相同。 – Cohars

回答

0

做一些更多的测试后,我想通了,它来自于浏览器(和Chrome在这种情况下),最终测试:

$.get("http://localhost:3000/api/users/slug") // 1 
$.get("http://localhost:3000/api/users/slug") // 2 
$.get("http://localhost:3000/api/other/route") // 3 
$.get("http://localhost:3000/api/other/route") // 4 

与Chrome的要求:

<-- GET /api/users/slug // 1 
<-- GET /api/other/route // 3 
--> GET /api/users/slug 200 2,004ms 183b 
<-- GET /api/users/slug // 2 
--> GET /api/other/route 200 2,004ms 183b 
<-- GET /api/other/route // 4 
--> GET /api/other/route 200 2,003ms 183b 
--> GET /api/users/slug 200 2,015ms 183b 

它需要4 secondes(2sc for 1 & 3 + 2sc for 2 & 4)。要求一个Firefox:

<-- GET /api/users/slug // 1 
<-- GET /api/users/slug // 2 
<-- GET /api/other/route // 3 
<-- GET /api/other/route // 4 
--> GET /api/users/slug 200 2,004ms 183b 
--> GET /api/users/slug 200 2,015ms 183b 
--> GET /api/other/route 200 2,003ms 183b 
--> GET /api/other/route 200 2,004ms 183b 

这一切都需要2秒。那么,它最终与服务器(或节点,koa,async)无关,它只是浏览器处理请求的方式。