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

  • 使用场景:前端首次发起请求获取数据,若失败则每隔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)
  }
相关推荐
ffqws_30 分钟前
Spring Boot 接收前端请求的四种参数方式
前端·spring boot·后端
是安迪吖1 小时前
企业资产管理系统练习
前端·ai
zhouwy1131 小时前
AI 编程工具结合 Figma MCP 实现前端设计高保真还原
前端·人工智能·figma
kyriewen1 小时前
WebAssembly:前端界的“外挂”,让C++代码在浏览器里跑起来
前端·c++·webassembly
悟空和大王1 小时前
核心 SDK 详细设计文档 (Visual-Render-SDK)
前端
AI砖家2 小时前
Claude Code Superpowers 安装使用指南:让 AI 编程从“业余”走向“工程化”
前端·人工智能·python·ai编程·代码规范
李白的天不白2 小时前
webpack 与axios 版本冲突问题
前端·webpack·node.js
Java后端的Ai之路2 小时前
模型调好了怎么给老板看?用这玩意儿5分钟出Demo,连前端都不用学:Gradio 6全栈实战指南
前端·机器学习·gradio
木斯佳2 小时前
前端八股文面经大全:中科星图前端日常实习(2026-04-29)·面经深度解析
前端
heRs BART3 小时前
spring-boot-starter和spring-boot-starter-web的关联
前端