async/await w/ koa 2 & mongoose

async/await w/ koa 2 & mongoose

本文关键字:amp mongoose koa await async      更新时间:2023-09-26

我目前正在玩Koa 2,具有async/await功能。假设我有 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 秒。你知道为什么没有吗?

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

在做了更多的测试后,我发现它来自浏览器(在这种情况下是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

使用铬请求:

<-- 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秒(2sc for 1 & 3 + 2sc for 2 & 4)。在火狐上请求:

<-- 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,异步)无关,这只是浏览器处理请求的方式。