How to use the CancelToken function from axios

Find comprehensive JavaScript axios.CancelToken code examples handpicked from public code repositorys.

axios.CancelToken is a factory function that creates a token used to cancel an ongoing Axios request.

74
75
76
77
78
79
80
81
82
83
request(opts, clbk) {
	var response = null;

	var error = null;

	const cancelTokenSource = axios.CancelToken.source();

	var aopts = {
		url: opts.uri,
		params: opts.qs,
fork icon9
star icon5
watch icon0

3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
  return actionType[type];

case 2:
  action = _context3.sent;
  axios = requestAxios || action.api && action.api.axios || axiosInterceptors || request;
  CancelToken = AxiosDefault.CancelToken;
  _context3.next = 7;
  return CancelToken.source();

case 7:
fork icon6
star icon9
watch icon0

How does axios.CancelToken work?

In Axios, you can cancel an ongoing request by using a CancelToken object. The axios.CancelToken is a factory function that creates a new CancelToken instance. To create a CancelToken, you call the axios.CancelToken factory function and pass it a cancel function as an argument. The cancel function is called when the cancel method is invoked on the CancelToken object. javascript Copy code {{{{{{{ const cancelTokenSource = axios.CancelToken.source(); In this example, cancelTokenSource is an object with two properties: token and cancel. The token property is a CancelToken instance that can be passed to an Axios request as the cancelToken option. The cancel property is a function that can be used to cancel the request. When you pass the CancelToken instance to an Axios request, Axios will register a cancellation callback that will be called if the request is cancelled. The cancellation callback will call the cancel function that was passed to the axios.CancelToken factory function. javascript Copy code {{{{{{{ class="!whitespace-pre hljs language-javascript">axios.get('/example', { cancelToken: cancelTokenSource.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); In this example, we pass the cancelTokenSource.token to an Axios GET request as the cancelToken option. If the request is cancelled, Axios will throw an error with the Cancel object, which can be caught using the catch block. The axios.isCancel function can be used to check if the error is a cancellation error, and the thrown.message will contain a message indicating that the request was cancelled. To cancel the request, you simply call the cancel method on the CancelToken instance: javascript Copy code {{{{{{{ class="!whitespace-pre hljs language-javascript">cancelTokenSource.cancel('Operation canceled by the user.'); In this example, we call the cancel method on the cancelTokenSource object and pass it a message to indicate why the operation was cancelled. Once the cancel method is called, the cancellation callback registered with Axios will be called, and the request will be cancelled.

4
5
6
7
8
9
10
11
12
13
14
15
const Report = require('../models/report.js');
const Wallet = require('../models/wallet.js');


const axios = require('axios');
const puppeteer = require('puppeteer');
const CancelToken = axios.CancelToken;
const fs = require("fs");


var storage = multer.diskStorage({
  destination: function (req, file, cb) {
fork icon0
star icon0
watch icon1

65
66
67
68
69
70
71
72
73
74
75
76
77




async function fetchWithTimeout(resource, options = {}) {
  const timeout = options?.timeout || 15000;


  const source = axios.CancelToken.source();
  const id = setTimeout(() => source.cancel(), timeout);
  try {
    const response = await axios({
      ...options,
fork icon0
star icon0
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios
  .get("/example", {
    cancelToken: source.token,
  })
  .then((response) => {
    console.log("Response:", response.data);
  })
  .catch((thrown) => {
    if (axios.isCancel(thrown)) {
      console.log("Request canceled", thrown.message);
    } else {
      console.error("Request error:", thrown);
    }
  });

setTimeout(() => {
  source.cancel("Operation canceled by the user.");
}, 1000);

In this example, we create a CancelToken object using axios.CancelToken.source(), which returns an object with two properties: token and cancel. We pass the token property to an Axios GET request using the cancelToken option. We then set a timeout to call the cancel function on the source object after one second. When the cancel function is called, Axios will throw a Cancel object, which can be caught using the catch block. We check if the error is a cancellation error using axios.isCancel and log a message indicating that the request was canceled. If the request is successful, the then block will be executed, and the response data will be logged to the console. If there is an error, but it's not a cancellation error, the catch block will be executed, and the error will be logged to the console.