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

  • 使用场景:前端首次发起请求获取数据,若失败则每隔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)
  }
相关推荐
jerrywus8 分钟前
用 AMD Radeon Cloud 免费跑 ComfyUI:从开机到打开界面
前端·agent·claude
学以智用10 分钟前
CKEditor5 完整详解
前端·后端
掘金者阿豪18 分钟前
数据库性能优化:一次慢查询背后,可能不只是SQL的问题
前端·后端
deli0072 小时前
锁过期了业务还没跑完:SETNX 分布式锁 1000 次并发实测
前端
不一样的少年_3 小时前
用了这 Skill,我觉得前端兄弟可以毕业了
前端·后端·agent
FRing033 小时前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
梦想很大很大3 小时前
一句“你好”用了 5671 Token:我在 Workrun 中追查 Agent 隐性成本的过程
前端·人工智能·后端
SameX3 小时前
HarmonyOS ArkTS 做动画 FPS 自适应降级的滞后窗口做法
前端
用户97887605390483 小时前
Canvas 处理大图时如何不卡住主线程:一次浏览器端批量压缩的调度实践
前端
鶴哥只手遮天3 小时前
# 《Electron 45.2.3 内核解剖》第 6 章 Node.js 集成:两个事件循环的婚姻
前端·electron·开源