取消请求

取消请求

¥Cancelling requests

在 axios 调用中设置 timeout 属性可处理与响应相关的超时。

¥Setting the timeout property in an axios call handles response related timeouts.

在某些情况下(例如网络连接不可用),尽早取消连接将使 axios 调用受益。如果不取消,axios 调用可能会挂起,直到父代码/堆栈超时(在服务器端应用中可能是几分钟)。

¥In some cases (e.g. network connection becomes unavailable) an axios call would benefit from cancelling the connection early. Without cancellation, the axios call can hang until the parent code/stack times out (might be a few minutes in a server-side applications).

要终止 axios 调用,你可以使用以下方法:

¥To terminate an axios call you can use following methods:

结合 timeout 和取消方法(例如 signal)应涵盖响应相关超时和连接相关超时。

¥Combining timeout and cancellation method (e.g. signal) should cover response related timeouts AND connection related timeouts.

signal:AbortController

v0.22.0 开始 axios 支持 AbortController 以 fetch API 方式取消请求:

¥Starting from v0.22.0 Axios supports AbortController to cancel requests in fetch API way:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()

使用最新的 AbortSignal.timeout() API [nodejs 17.3+] 的超时示例:

¥Example with a timeout using latest AbortSignal.timeout() API [nodejs 17.3+]:

axios.get('/foo/bar', {
   signal: AbortSignal.timeout(5000) //Aborts request after 5 seconds
}).then(function(response) {
   //...
});

使用超时辅助函数的示例:

¥Example with a timeout helper function:

function newAbortSignal(timeoutMs) {
  const abortController = new AbortController();
  setTimeout(() => abortController.abort(), timeoutMs || 0);

  return abortController.signal;
}

axios.get('/foo/bar', {
   signal: newAbortSignal(5000) //Aborts request after 5 seconds
}).then(function(response) {
   //...
});

CancelToken deprecated

你还可以使用 CancelToken 取消请求。

¥You can also cancel a request using a CancelToken.

axios 取消令牌 API 是基于撤回的 可撤销的 promise 提案

¥The axios cancel token API is based on the withdrawn cancelable promises proposal.

此 API 自 v0.22.0 起已弃用,不应在新项目中使用

¥This API is deprecated since v0.22.0 and shouldn't be used in new projects

你可以使用 CancelToken.source 工厂创建取消令牌,如下所示:

¥You can create a cancel token using the CancelToken.source factory as shown below:

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.');

你还可以通过将执行函数传递给 CancelToken 构造函数来创建取消令牌:

¥You can also create a cancel token by passing an executor function to the CancelToken constructor:

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();

注意:你可以使用相同的取消令牌/信号取消多个请求。

¥Note: you can cancel several requests with the same cancel token / signal.

在过渡期间,你可以使用两种取消 API,即使是针对同一个请求:

¥During the transition period, you can use both cancellation APIs, even for the same request:

const controller = new AbortController();

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token,
  signal: controller.signal
}).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.');
// OR
controller.abort(); // the message parameter is not supported