async/await w/ koa 2 & mongoose
async/await w/ koa 2 & mongoose
我目前正在玩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,异步)无关,这只是浏览器处理请求的方式。
相关文章:
- jquery点击函数select&取消选择
- 使用promise和mongoose对文档进行排序
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- Angular js-返回一个包含类似
- 一点javascript元编程&可链接的设置器
- 如何缩短MongoDB ObjectId并在Mongoose模式中使用它
- 通过JSON&比较时间
- Jquery模板,如果xx&&如果yy
- jQuery工具验证器自定义效果-添加&消除影响
- Twitter引导程序Typeahead-Id&标签
- AngularJS&JSON-从Previous&下一个对象
- 什么是&&在没有if的行中的变量之间
- mongoose.connect undefined不是一个函数
- 关于引入外部javascript文件的问题&css通过https
- 指令的模板必须只有一个根元素:With restrict E&替换true
- 使用ajax的服务器端分页&jQuery
- Javascript,如果条件在没有&&逻辑运算符当&&它不起作用
- 如何使用dropzone&vueJs
- 如何准确执行加载脚本&退出弹出窗口
- 如何添加CSS&JavaScript进入Windows窗体应用程序C#.net