我正在使用Koa2和node-sqlite3并遇到一个问题,我无法让Koa在返回身体之前等待db调用返回
简化示例:
app.get('/:name/:nickname', function (ctx) {
var queryParams = [ctx.params.name, ctx.params.nickname]
db.get("SELECT nickname FROM users WHERE name = ? AND nickname = ?", queryParams, function (err,result) {
if (result == null) {
console.log('Add new nickname')
db.run("INSERT INTO users (name, nickname) VALUES (?, ?)", queryParams)
ctx.body = 'Inserted user ' + ctx.params.nickname
} else {
console.log('Return existing nickname')
ctx.body = result.nickname
}
})
console.log('This is after')
})
总会返回如下内容:
这是之后的 添加新昵称
如何让koa等待sqlite结果?
修改
道歉,这是一个简单的承诺:
app.get('/:name/:nickname', async (ctx, next) => {
await new Promise((resolve, reject) => {
var queryParams = [ctx.params.name, ctx.params.nickname]
db.get("SELECT nickname FROM users WHERE name = ? AND nickname = ?", queryParams, function (err,result) {
if (result == null) {
// Add the name if not in DB
db.run("INSERT INTO users (name, nickname) VALUES (?, ?)", queryParams)
ctx.body = 'Inserted user ' + ctx.params.nickname
} else {
// Return nickname if in DB
ctx.body = row.nickname
}
resolve()
})
})
console.log('This is after')
})