如何根据用户操作动态调整多个API请求的优先级?

设计师鑫钰 阅读 16

在开发数据表格时同时发起筛选、分页和搜索请求,但关键筛选数据总是最后返回导致界面卡顿。之前尝试用axios.all并发请求,但关键数据因为后端逻辑总是最后回来,有什么办法能让筛选请求优先完成吗?

试过给筛选请求设置超时:timeout: 1000但影响了可靠性。也尝试过手动用axios.CancelToken在新请求到来时取消旧请求,但优先级逻辑写得一团糟,有没有更优雅的方案?


// 当前混乱的尝试
handleSearch() {
  if (this.cancelSearch) this.cancelSearch('新搜索开始')
  const source = axios.CancelToken.source()
  this.cancelSearch = source.cancel
  axios.get('/api/data', { 
    params: this.query,
    cancelToken: source.token 
  }).then(res => {
    // 处理数据
  })
}
我来解答 赞 5 收藏
二维码
手机扫码查看
1 条解答
UP主~瑞丽
用请求队列控制优先级,关键筛选单独处理。代码如下:

class ApiQueue {
constructor() {
this.queue = []
this.processing = false
}

add(request, priority = 0) {
const item = { request, priority }
this.queue.push(item)
this.queue.sort((a, b) => b.priority - a.priority)
this.run()
}

run() {
if (this.processing) return
const next = this.queue.shift()
if (!next) return

this.processing = true
next.request().finally(() => {
this.processing = false
this.run()
})
}
}

const apiQueue = new ApiQueue()

// 使用方式
apiQueue.add(() => axios.get('/api/filter', { params: filterParams }), 1) // 高优先级
apiQueue.add(() => axios.get('/api/search', { params: searchParams }), 0) // 普通优先级

搞定
点赞 2
2026-02-14 16:11