首页 > 解决方案 > 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,哪一个是合理的方式?非常感谢。

标签: node.jsejskoakoa2

解决方案


最佳做法是使用第二种方式。async/await 机制旨在用.then(). 这是一篇很好的文章(不是我的):https ://nemethgergely.com/async-function-best-practices/


推荐阅读