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

  • 使用场景:前端首次发起请求获取数据,若失败则每隔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)
  }
相关推荐
LinXunFeng3 小时前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
乘风gg7 小时前
为什么AI 时代来临,大部分人吃不到红利
前端·ai编程·claude
恋猫de小郭7 小时前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter
IT_陈寒7 小时前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
恋猫de小郭7 小时前
解读 Android 17 全新内存限制,有没有“豁免”后门?
android·前端·flutter
Hyyy9 小时前
理解LLM的基本工作原理:预训练、微调、推理的区别
前端
Gatlin9 小时前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
Pedantic9 小时前
本地通知(Local Notifications)学习笔记
前端
森蓝情丶10 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端
爱勇宝10 小时前
干了近 8 年,一夜之间被裁:AI 时代,程序员最该害怕的不是 AI
前端·后端·程序员