I am trying to do a post request that will do the following.
Here is the code I have, it works to update the dataase, I threw in some console.logs() to see the flow. the current code outputs "World Hello" instead of "Hello World". How could I make the output be "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))
});
If you add in a return on the inner promise, that should fix things. See this answer for details on why. You could also refactor things a bit to use await
(right now your async
keyword is going to waste), which would un-nest the blocks, and clarify the flow. Note: this code is not tested, but it's just changing your code to use async/await so I think it will work:
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)
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.