axios 取消請求


解決思路

在發送第二次請求的時候如果第一次請求還未返回,則取消第一次請求,以保證后發送的請求返回的數據不會被先發送的請求覆蓋。

axios官方文檔取消請求說明

方法一:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
方法二:
const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

可行方案

代碼如下:

/* 接口listApi.getList方法如下 */
const CancelToken = axios.CancelToken
let cancel
getVideoList ({
  key
}) {
  return axiosInstance.post('/video/list', {
    key
  }, {
    cancelToken: new CancelToken(function executor (c) {
      cancel = c
    })
  })
},
cancelRequest () {
  // 第一次執行videoService.cancelRequest()時還未發送getVideoList請求,會報錯,添加如下判斷
  if (typeof cancel === 'function') {
    // 取消請求
    cancel()
  }
}

/* 頁面中獲取列表的函數 */
getList (query, cb) {
  // 取消之前的請求
  listApi.cancelRequest()
  // 發送請求
  listApi.getVideoList({key: 'value'}).then(resp => {
    // handle response data
  }).catch(err => {
    if (axios.isCancel(err)) {
      console.log('Request canceled!')
    } else {
      this.$message.error(err.message)
    }
  })
}

此時重復發送多次`getVideoList請求時,會取消之前發送的請求保證返回數據為最后一次請求返回的數據。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM