iwenwikiiwenwiki
首页
  • 指尖联盟
  • 百战商城
  • uniapp
  • 网易云音乐
  • 安心食疗
前端面试题
鸿蒙面试题
华为认证题库
项目列表
毕设与课设
  • 仓颉
  • 前端
  • HarmonyOS
视频教程
首页
  • 指尖联盟
  • 百战商城
  • uniapp
  • 网易云音乐
  • 安心食疗
前端面试题
鸿蒙面试题
华为认证题库
项目列表
毕设与课设
  • 仓颉
  • 前端
  • HarmonyOS
视频教程
  • 前端

前端

轮询

一、业务需求:后端是授权(企业数据)接口,授权成功与否需要等待的时间比较长,返回的时间在1-2分钟之间,所以前端设置等待状态,需要每间隔一段时间去获取一次授权结果

二、封装轮询代码块,这里使用 setTimeout 实现,要比 setInterval 更好一些

/**
     * @descripting 轮询功能
     * @param {Function} fn     网络请求方法
     * @param {Object} data     网络请求参数
     * @param {Number} delay    轮询间隔时间
     */

let timer = null

export function polling(fn, data, delay = 5000) {
    return new Promise((resolve, reject) => {
        fn(data).then(res => {
            resolve(res)
        }).catch(error => {
            timer = setTimeout(() => {
                resolve(polling(fn, data, delay = 5000));
            }, delay)
        })
    })
}


export function clearPolling(){
    clearTimeout(timer)
}

三、业务中使用,特别提醒的是,一定要记得清除定时器

/**
 * 网络请求函数
 * 判断-供应链授权结果
 */
export function getSellerChainAuth(data) {
    return request({
        url: '/report/rollback/getAuthResult',
        method: 'post',
        data
    })
}
/**
 * 轮询调用
 */
polling(getSellerChainAuth, { authKey: authStore.authKey }, 5000).then(res => {
    httpSellerChainPDF(authStore.authKey, dueDiligenceStore.keyNo)
})

/**
 * 在页面被销毁之前需要清除轮询,避免副作用
 */
onUnmounted(() => {
    clearPolling()
})

四、推荐一个最近用过的网络请求库 VueRequest,兼容 Vue 2 & 3、所有数据都具有响应式、轮询请求、节流请求与防抖请求等等

Last Updated:
Contributors: iwen