【问题标题】:async/await w/ koa 2 & mongoose带有 koa 2 和猫鼬的异步/等待
【发布时间】:2016-06-22 14:28:58
【问题描述】:

我目前正在使用带有异步/等待功能的 Koa 2。假设我有 2 条路线,都在数据库上查询。一个查询是常规且简单的查询。第二个是我所做的:

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 秒。你知道为什么不需要吗?

这是一个很长的问题,我试图为您提供所有相关信息。谢谢!

【问题讨论】:

  • 使用await new Promise(resolve =&gt; setTimeout(resolve, 2000));模拟延迟不是更容易吗?
  • 是的,当然!我想模拟一个慢的 mongodb 请求,不修改 JS 代码,但结果是一样的。

标签: javascript asynchronous async-await ecmascript-6 koa


【解决方案1】:

在做了更多测试后,我发现它来自浏览器(在本例中是 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 为 2sc + 2 和 4 为 2sc)。在 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、koa、async)无关了,只是浏览器处理请求的方式而已。

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2018-08-30
    • 2019-05-10
    • 2018-06-11
    • 2020-10-16
    • 2019-12-12
    • 2018-04-13
    • 2019-02-15
    • 2020-08-01
    相关资源
    最近更新 更多