[英]How to use async reasonably in koa2
我对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
,哪种是合理的方法? 非常感谢。
最佳实践是使用第二种方法。 异步/等待机制旨在用.then()
代替链接承诺。 这是一篇很好的文章(不是我的): https : //nemethgergely.com/async-function-best-practices/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.