解决多次连续请求出现冲突问题

问题: 下拉加载的时候,会多次触发并调用getLiveData,由于该函数共享一个currentPage变量,导致数据不安全问题

错误代码:

const getLiveData = async () => {
     if(currentPage.value >= totalPage.value) return false
 
     const res = await requestLiveData(currentPage.value + 1)
     currentPage.value = currentPage.value + 1
     liveData.value.push(...res.list)
     console.log(res.list)
     return true
}

错误原因分析:由于vue是非阻塞的,当第一次调用到const res = await requestLiveData(currentPage.value + 1)  这一步的时候,需要去请求网络,res变量会等待获得响应资源,又由于是非阻塞的,下一个异步请求会执行,而这个时候currentPage.value还没有更新,即这次请求的参数其实是错误的,将会导致数据错误。

解决:

添加一个锁变量isFetching

const getLiveData = async () => {
        if(isFetching)  return true
        if(currentPage.value >= totalPage.value) return false
        isFetching = true;
        try{
            const res = await requestLiveData(currentPage.value + 1)
            currentPage.value = currentPage.value + 1
            liveData.value.push(...res.list)
            console.log(res.list)
            return true
        }finally{
            isFetching = false;
        }
        
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值