• usage
const CancelToken = axios.CancelToken; 
let cancel;  
axios.get('/user/12345', {   
    cancelToken: new CancelToken(function executor(c) {     
        // The executor function takes a cancel function as an argumentcancel = c; })});// cancel the request cancel();

Copy the code
  • Pseudocode implementation
function Cancel(message) {
  this.message = message;
}

function CancelToken(executor) {
  if (typeofexecutor ! = ='function') {
    throw new TypeError('executor must be a function.');
  }

  var resolvePromise;
  this.promise = new Promise(function promiseExecutor(resolve) {
    resolvePromise = resolve;
  });

  var token = this;
  executor(function cancel(message) {
    if (token.reason) {
      // Cancellation has already been requested
      return;
    }

    token.reason = new Cancel(message);
    resolvePromise(token.reason);
  });
}


function axios(config) {
  return new Promise((resolve, reject) = >{
    var xhr = new XMLHttpRequest(),
        method = "GET",
        url = "/";

    if(config.cancelToken) {
      config.cancelToken.promise.then((cancel) = > {
        xhr.abort();
        reject(cancel);
      });
    }
    xhr.open(method, url, true); xhr.send(); })}let cancel;
axios({
  url: '/'.cancelToken: new CancelToken(function executor(c) {
    // The executor function takes a cancel function as an argument
    cancel = c;
  })
})

cancel()
Copy the code

Calling Cancel causes the CancelToken instance property promise resolve to be called

config.cancelToken.promise.then((cancel) = > {
    xhr.abort();
    reject(cancel);
});
Copy the code

Cancel Ajax Rejected throws an error