前端发起更改数据请求后再获取后端数据发现数据并未更改的一个解决办法

前端发起更改数据请求后再获取后端数据发现数据并未更改的一个解决办法

问题再现

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是异步的,需要考虑执行顺序

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嗯嗯你说的对

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值