如何在Koa2中合理使用异步

时间:2018-07-11 18:01:59

标签: node.js ejs koa 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,哪种方法合理?非常感谢。

1 个答案:

答案 0 :(得分:1)

最佳做法是使用第二种方法。异步/等待机制旨在用const myMethod = (someValue: SomeInterface[]): RetType => { let someVar: RetType = {}; someValue.forEach((v: SomeInterface) => { const someVarVName = someVar[v.name] || []; // make sure it's set someVarVName.push(v); someVar[v.name] = someVarVName; // copy back in case it's a new array }); //someVar.keyName = 'value' return someVar } 代替链接承诺。这是一篇不错的文章(不是我的):https://nemethgergely.com/async-function-best-practices/