node.js - koa2中如何合理使用async
问题描述
我对 koa2 中两种不同的写法感到困惑。我的需求是
从 mysql 获取两个结果,并将它们传递给ejs
.
第一种方式
await mysqlModel.getThePeopleCount() //data from table `people`
.then(async(result) => {
let countpeople = result[0].peoplecount
await mysqlModel.getTheMyInfo() //data from table `myinfo`
.then(async(result) => {
await ctx.render('people', {
myinfo: result[0].name,
countpeoples:countpeople
});
})
})
第二种方式
let results1 = await mysqlModel.getThePeopleCount()
let results2 = await mysqlModel.getTheMyInfo()
await ctx.render('people', {
myinfo: result2[0].name,
countpeoples:result1[0].peoplecount
});
数据库是mysql
,哪一个是合理的方式?非常感谢。
解决方案
最佳做法是使用第二种方式。async/await 机制旨在用.then()
. 这是一篇很好的文章(不是我的):https ://nemethgergely.com/async-function-best-practices/
推荐阅读
- php - 如何使用(“jQuery”)从动态数据中获取“ajax”表
- elasticsearch - 缩小弹性搜索集群
- cakephp-3.0 - CakePHP 3 使用 ORM 加入辅助键
- entity-framework - InMemory 数据库 (EF) 的 Liquibase 变更集
- webpack - 在 webpack 构建后 Highlight.js 语法突出显示不起作用
- python - 在同一类 OpenCV Python 中的两个不同函数中使用 VideoCapture()
- android - Flutter SDK 没有平滑渐变?
- vba - Vba 电子邮件生成器,来自 excel 电子表格的主题
- android - ionic cordova run android正在给出gradle错误
- laravel - Laravel 克隆/多集合到模型插入