首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步/等待w/ koa 2和猫鼬

异步/等待w/ koa 2和猫鼬
EN

Stack Overflow用户
提问于 2016-03-08 15:03:31
回答 1查看 1K关注 0票数 1

我目前正在使用Koa 2,使用异步/等待功能。假设我有两条路线,都是查询DB的。一个查询是一个常规的、简单的查询。关于第二个问题,我所做的是:

代码语言:javascript
复制
q.$where = `function() {
  var d = new Date((new Date()).getTime() + 2000);
  while (d > (new Date())) { }; return true;}`
return await this.findOne(q)

$where添加一个2秒延迟来模拟慢速查询。如果我请求这条路线(慢速路线)两次这样的话:

代码语言:javascript
复制
$.get('/api/users/slug')
$.get('/api/users/slug')

服务器记录:

代码语言:javascript
复制
<-- 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秒后到达服务器。

鉴于如果我要求:

代码语言:javascript
复制
$.get('/api/users/slug')
$.get('/api/other/route')

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

代码语言:javascript
复制
<-- GET /api/users/hugo
<-- GET /api/other/route
--> GET /api/other/route 200 3ms 183b
--> GET /api/users/hugo 200 2,004ms 183b

我们看到第二个请求在第一个请求之后立即到达服务器。

实际上我希望第一次考试能给我

代码语言:javascript
复制
<-- 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秒。你知道为什么不需要吗?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-08 15:31:31

在做了更多的测试之后,我发现它来自浏览器(在本例中是Chrome ),最后的测试是:

代码语言:javascript
复制
$.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请求:

代码语言:javascript
复制
<-- 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上请求:

代码语言:javascript
复制
<-- 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、异步)无关,它只是浏览器处理请求的方式。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35870849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档