Skip to content
大纲

fetch取消请求

创建接口控制器实例AbortController,然后将signal信号传入fetch请求中。在业务逻辑中使用controller.abort()取消请求

js
export function fetchWithCancel (timeout = 5000) {
  return function (url: string, option: {[x: string]: any} = {}) {
    return new Promise((res, rej) => {
      const controller = new AbortController()
      /* 外部传入的一起监听到 */
      if (option.signal) {
        const signal = option.signal
        signal.addEventListener('abort', () => {
          controller.abort()
        })
      }
      /* 传入标签,关联起来 */
      option.signal = controller.signal
      fetch(url, option).then(res, rej)
      setTimeout(() => {
        rej(new Error('请求超时'))
        controller.abort()
      }, timeout)
    })
  }
}

axios取消请求

使用axios.CancelToken.source()创建源,然后传入请求中,在业务逻辑中使用source.cancel('请求取消的原因')

js
const source = axios.CancelToken.source()

axios.get('/api/data', {
  cancelToken: source.token
}).then((response) => {
  // 请求成功处理
}).catch((error) => {
  // 错误处理
})

// 在需要的时候取消请求
source.cancel('请求取消的原因')

``

Released under the MIT License.