async / await w / koa 2&猫鼬

时间:2016-03-08 15:03:31

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

我目前正在玩Koa 2,使用async / await功能。让我们说我有2条路线,都在DB上查询。一个查询是常规&很容易。在第二个是我做的:

$where

$.get('/api/users/slug') $.get('/api/users/slug') 添加 2秒延迟来模拟慢查询。如果我要求两次这样的路线(慢速路线):

<-- 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

服务器记录:

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

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

<-- 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

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

我实际上期待第一次测试给我

<CalendarView
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"/>

所以整件事需要2秒钟而不是4秒。你知道它为什么没有?

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

1 个答案:

答案 0 :(得分: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(2scs为1&amp; 3 + 2sc为2&amp; 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)无关,它只是浏览器处理请求的方式。