前端發起更改數據請求后再獲取后端數據發現數據并未更改的一個解決辦法
問題再現
async function refuseRefund(id,type){if(confirm('確定拒絕?')){await fetch('http://127.0.0.1:3000/api/refuseRefund', {method: 'POST',headers: {'Content-type': 'application/json'},body: JSON.stringify({id: id,type: type})}).then(response => {if (!response.ok) {throw new Error('Network response was not ok');}return response.json();}).then(data => {//重載addOrdersList();}).catch(error => {console.error('Error:', error);}); }
}async function addOrdersList() {buyShipOrders = await getAll('buy');console.log(buyShipOrders);
}
我們向后端發起一個http請求來修改數據庫的某個值,然后再重新獲取數據,發現數據并未更改,奇怪,明明函數里用了await()
原因
原來后端node.js函數出了問題
app.post('/api/refuseRefund', (req, res) => {const orderId = req.body.id;const type = req.body.type;pool.query(`UPDATE ${type} set status = ? WHERE id = ? `, ['已拒絕',orderId], (error, results) => {if (error) {console.error('Error querying database:', error);res.status(500).send('Internal Server Error');return;}});res.json({status: true});
});
nodejs也是js,那么既然是js,那么它就是異步的,也就是說,res.json()會先于pool.query()執行,數據庫修改也是需要時間的,這就回造成數據庫還沒處理完就返回了res,前端這邊拿到res也是立馬再發起了一個獲取數據的請求,由于數據庫還沒修改完,所以返回的是修改前的值
解決
將res.json()放在pool.query()里面
app.post('/api/refuseRefund', (req, res) => {const orderId = req.body.id;const type = req.body.type;pool.query(`UPDATE ${type} set status = ? WHERE id = ? `, ['已拒絕',orderId], (error, results) => {if (error) {console.error('Error querying database:', error);res.status(500).send('Internal Server Error');return;}res.json({status: true});});
});
總結
node.js是異步的,需要考慮執行順序