我目前正在使用Koa 2,使用异步/等待功能。假设我有两条路线,都是查询DB的。一个查询是一个常规的、简单的查询。关于第二个问题,我所做的是:
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秒。你知道为什么不需要吗?
这是一个很长的问题,我试着给你所有相关的信息。谢谢!
发布于 2016-03-08 15:31:31
在做了更多的测试之后,我发现它来自浏览器(在本例中是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次(1和3+2 2sc为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秒。
最后,它与服务器(或节点、node、异步)无关,它只是浏览器处理请求的方式。
https://stackoverflow.com/questions/35870849
复制相似问题