[英]Knex.js with Express, How can I knex.commit followed by a knex.select query?
我正在嘗試執行將執行以下操作的發布請求。
這是我擁有的代碼,它可以更新數據酶,我投入了一些 console.logs() 來查看流程。 當前代碼輸出“World Hello”而不是“Hello World”。 如何使 output 成為“Hello World”?
app.post('/checkin', async (req, res) => {
db('assets').select('status').where('id', '=', req.body.id)
.then(data => {
currentStatus = data[0].status;
if (currentStatus.slice(0, 10) === 'In Use By ' || currentStatus === 'Quarantine') {
db('assets')
.where('id', '=', req.body.id)
.update({ status: 'Available', comments: '' }).then(db.commit)
.then(console.log('Hello'))
}
})
.then(console.log('World'))
.then(db('assets').select('*').where('id', '=', req.body.id)
.then(data => res.status(200).json(data[0])))
.catch(error => res.status(400).json(error))
});
如果您在內部 promise 上添加返回,那應該可以解決問題。 有關原因的詳細信息,請參閱此答案。 您還可以重構一些東西以使用await
(現在您的async
關鍵字會浪費),這將取消嵌套塊並澄清流程。 注意:此代碼未經測試,但它只是將您的代碼更改為使用 async/await,所以我認為它會起作用:
app.post('/checkin', async (req, res) => {
try {
const data = await db('assets').select('status').where('id', '=', req.body.id)
currentStatus = data[0].status;
if (currentStatus.slice(0, 10) === 'In Use By ' || currentStatus === 'Quarantine') {
await db('assets')
.where('id', '=', req.body.id)
.update({ status: 'Available', comments: '' })
await db.commit();
console.log('Hello');
}
console.log('World')
const secondData = await db('assets').select('*').where('id', '=', req.body.id)
res.status(200).json(secondData[0])
} catch (error) {
res.status(400).json(error)
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.