Path: blob/master/node_modules/axios/lib/cancel/CancelToken.js
1126 views
'use strict';12var Cancel = require('./Cancel');34/**5* A `CancelToken` is an object that can be used to request cancellation of an operation.6*7* @class8* @param {Function} executor The executor function.9*/10function CancelToken(executor) {11if (typeof executor !== 'function') {12throw new TypeError('executor must be a function.');13}1415var resolvePromise;1617this.promise = new Promise(function promiseExecutor(resolve) {18resolvePromise = resolve;19});2021var token = this;2223// eslint-disable-next-line func-names24this.promise.then(function(cancel) {25if (!token._listeners) return;2627var i;28var l = token._listeners.length;2930for (i = 0; i < l; i++) {31token._listeners[i](cancel);32}33token._listeners = null;34});3536// eslint-disable-next-line func-names37this.promise.then = function(onfulfilled) {38var _resolve;39// eslint-disable-next-line func-names40var promise = new Promise(function(resolve) {41token.subscribe(resolve);42_resolve = resolve;43}).then(onfulfilled);4445promise.cancel = function reject() {46token.unsubscribe(_resolve);47};4849return promise;50};5152executor(function cancel(message) {53if (token.reason) {54// Cancellation has already been requested55return;56}5758token.reason = new Cancel(message);59resolvePromise(token.reason);60});61}6263/**64* Throws a `Cancel` if cancellation has been requested.65*/66CancelToken.prototype.throwIfRequested = function throwIfRequested() {67if (this.reason) {68throw this.reason;69}70};7172/**73* Subscribe to the cancel signal74*/7576CancelToken.prototype.subscribe = function subscribe(listener) {77if (this.reason) {78listener(this.reason);79return;80}8182if (this._listeners) {83this._listeners.push(listener);84} else {85this._listeners = [listener];86}87};8889/**90* Unsubscribe from the cancel signal91*/9293CancelToken.prototype.unsubscribe = function unsubscribe(listener) {94if (!this._listeners) {95return;96}97var index = this._listeners.indexOf(listener);98if (index !== -1) {99this._listeners.splice(index, 1);100}101};102103/**104* Returns an object that contains a new `CancelToken` and a function that, when called,105* cancels the `CancelToken`.106*/107CancelToken.source = function source() {108var cancel;109var token = new CancelToken(function executor(c) {110cancel = c;111});112return {113token: token,114cancel: cancel115};116};117118module.exports = CancelToken;119120121