Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

@nuxtjs/axios开发项目时 如何取消请求?

export default function (context) {
  let { $axios, store, redirect } = context
  $axios.onRequest(config => {
   
    return config
  })

  $axios.onError(error => {
  
  })
  $axios.onResponse(resp => {
    
  })
}

方法里面的$axios上没有cancelToken的方法,这里应该如何当一个请求执行后在尚未返回数据之前,如果再次调用,就取消这次新的请求。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你应该用一个变量标记,禁止该请求发出。cancelToken并不是取消请求,而是不接收该请求的返回值。
我解决过类似的问题,比如按钮多次点击只让第一次有效,除非第一次点击的请求已经返回。

function singleClick(func, manualDone = false) {
  let lock = false
  return function (...args) {
    if (lock) return
    lock = true
    const done = () => lock = false
    if (manualDone) return func.call(this, ...args, done)
    const promise = func.call(this, ...args)
    promise ? promise.finally(done) : done()
    return promise
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...