umijs / umi-request

A request tool based on fetch.
2.21k stars 335 forks source link

怎么正确的调用isCancel并传参 #308

Open leehomeok opened 2 years ago

leehomeok commented 2 years ago

image

我在 request的拦截器给每个请求加上了cancelToken

function addPending(config) {
  const pendingKey = getPendingKey(config);
  config.cancelToken = config.cancelToken || new Reqs.CancelToken((cancel) => {
    if (!pendingMap.has(pendingKey)) {
      pendingMap.set(pendingKey, cancel);
    }
  });
}

async function errHandler(response: Response, options: RequestOptionsInit, resJson: any) {
  const res = resJson ? resJson : await response?.clone?.()?.json?.() || {}
  console.log('isCancel', Reqs.isCancel(options), options)
  if(Reqs.isCancel(options.cancelToken)){
    console.log('Request canceled', options.message);
    return
  }
}

在response的时候 调用isCancel方法判断, 但每次都返回的false, 查看源码后,发现isCancel方法是判断传入的对象是否有CANCEL这个属性, 且CANCEL == true

如上截图,传参是否应该为 .cancelToken.promise

leehomeok commented 2 years ago

t通过查阅文档,发现isCancel 方法,应该放在errorHandler 异常处理函数里面

const errorHandler = (error: { response:  Response , request}) => {
  const { response, request } = error
 if(Reqs.isCancel(error)) {}

}