关于前端处理后端轮询的操作 (总结)

  • 使用场景:前端首次发起请求获取数据,若失败则每隔1s发起一次知道成功获取数据为止
  • 解决方案: 使用轮询操作,涉及定时器的使用和关闭
    (使用vue2代码为例)
js 复制代码
data() {
    return {
      pollingResult_en: null, // 处理轮询结果
      bizId_en: ''  // 请求需要携带的参数
    }
  },
  computed: {   // 注意computed和watch的区别
    pollingData() {
      return this.pollingResult_en
    }
  },
  watch: {
    pollingData: function (newval) {
    // 请求数据为null,失败,则轮询
      if (newval == null) {  
        var timer = setInterval(() => {
          setTimeout(() => {
            this.fetchResult(this.bizId_en)
          }, 0);
        }, 1000);
      } else {
        // 请求数据成功,则调用上传文件窗口
        this.$refs['upload'].$children[0].$refs.input.click()
        clearInterval(timer) 
      }
      // 页面关闭的时候结束轮询,使用$once(eventname, eventhandler) 一次性监听事件,beforeDestroy在路由跳转的时候不会触发
      this.$once('hook:beforeDestroy', () => {
        clearInterval(timer)
      })
    }
  },
  methods: {
  // 查询接口调用
	  fetchResult() {
	  	 fetchScanResult({ bizId: this.bizId }).then(res => {
	        this.pollingResult = res.data
	      })
	  	}	
  }

下面是一个自己写的一个具体应用中:

js 复制代码
  methods: {
  // 查询接口调用
	  fetchResult() {
	  	 fetchScanResult({ bizId: this.bizId }).then(res => {
	        if(res.data){
	        // 关闭定时器
	          clearInterval(this.timer)
	          console.log('获取数据成功')
	        } else {
	          // 轮询
	          this.timer = setInterval(()=>{
	          	setTimeout(() => {
	          		this.fetchResult()
	          	}, 0)
	          }, 1000)
	        }
	      })
	  	}	
  },
  beforeDestroy() {
  	this.clearInterval(this.timer)
  }
相关推荐
恋猫de小郭42 分钟前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅7 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60618 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了8 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅8 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅8 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅9 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment9 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅9 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊9 小时前
jwt介绍
前端