💡 一、什么时候需要用到"轮询"?
轮询适合用于:
后端处理时间不确定,前端需要持续等待结果的场景。
🔹 常见业务场景:
场景 说明
✅ 文件上传后等待处理结果 后端要转码、分析、生成报告等
✅ 任务提交后等待完成 比如导出Excel、生成PDF、生成报表
✅ 审批/支付系统 比如轮询支付结果、风控校验结果
✅ 异步交易(你系统中的"债券下达指令") 提交指令 → 后台风控处理 → 轮询查结果
✅ 消息通知 / 状态更新 实时性不高,又不能用WebSocket时
1️⃣ 提交任务(调用接口A)
2️⃣ 拿到任务ID(taskId)
3️⃣ 每隔几秒查询一次任务状态(接口B)
4️⃣ 如果状态为"成功/失败" → 停止轮询
5️⃣ 如果超过最大次数还没结果 → 提示超时
typescript
export default {
data() {
return {
timer: null,
timerCount: 0,
};
},
methods: {
async startPolling(taskId) {
this.loading = true;
this.timerCount = 0;
this.timer = setInterval(async () => {
this.timerCount++;
const res = await this.$http.get(`/api/taskStatus/${taskId}`);
if (res.data.status === 'SUCCESS' || this.timerCount > 10) {
clearInterval(this.timer);
this.loading = false;
if (res.data.status === 'SUCCESS') {
this.$message.success('任务完成 ✅');
} else {
this.$message.warning('任务超时,请稍后重试 ⚠️');
}
}
}, 3000);
},
beforeDestroy() {
clearInterval(this.timer);
},
},
};
setInterval 3秒种发一次轮循
timerCount是计数器
轮循调用的API接口: const res = await this.http.get('/api/taskStatus/http.get(`/api/taskStatus/http.get('/api/taskStatus/{taskId}`);
clearInterval(this.timer); 清除计数器