Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/node_modules/axios/lib/cancel/CancelToken.js
1126 views
1
'use strict';
2
3
var Cancel = require('./Cancel');
4
5
/**
6
* A `CancelToken` is an object that can be used to request cancellation of an operation.
7
*
8
* @class
9
* @param {Function} executor The executor function.
10
*/
11
function CancelToken(executor) {
12
if (typeof executor !== 'function') {
13
throw new TypeError('executor must be a function.');
14
}
15
16
var resolvePromise;
17
18
this.promise = new Promise(function promiseExecutor(resolve) {
19
resolvePromise = resolve;
20
});
21
22
var token = this;
23
24
// eslint-disable-next-line func-names
25
this.promise.then(function(cancel) {
26
if (!token._listeners) return;
27
28
var i;
29
var l = token._listeners.length;
30
31
for (i = 0; i < l; i++) {
32
token._listeners[i](cancel);
33
}
34
token._listeners = null;
35
});
36
37
// eslint-disable-next-line func-names
38
this.promise.then = function(onfulfilled) {
39
var _resolve;
40
// eslint-disable-next-line func-names
41
var promise = new Promise(function(resolve) {
42
token.subscribe(resolve);
43
_resolve = resolve;
44
}).then(onfulfilled);
45
46
promise.cancel = function reject() {
47
token.unsubscribe(_resolve);
48
};
49
50
return promise;
51
};
52
53
executor(function cancel(message) {
54
if (token.reason) {
55
// Cancellation has already been requested
56
return;
57
}
58
59
token.reason = new Cancel(message);
60
resolvePromise(token.reason);
61
});
62
}
63
64
/**
65
* Throws a `Cancel` if cancellation has been requested.
66
*/
67
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
68
if (this.reason) {
69
throw this.reason;
70
}
71
};
72
73
/**
74
* Subscribe to the cancel signal
75
*/
76
77
CancelToken.prototype.subscribe = function subscribe(listener) {
78
if (this.reason) {
79
listener(this.reason);
80
return;
81
}
82
83
if (this._listeners) {
84
this._listeners.push(listener);
85
} else {
86
this._listeners = [listener];
87
}
88
};
89
90
/**
91
* Unsubscribe from the cancel signal
92
*/
93
94
CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
95
if (!this._listeners) {
96
return;
97
}
98
var index = this._listeners.indexOf(listener);
99
if (index !== -1) {
100
this._listeners.splice(index, 1);
101
}
102
};
103
104
/**
105
* Returns an object that contains a new `CancelToken` and a function that, when called,
106
* cancels the `CancelToken`.
107
*/
108
CancelToken.source = function source() {
109
var cancel;
110
var token = new CancelToken(function executor(c) {
111
cancel = c;
112
});
113
return {
114
token: token,
115
cancel: cancel
116
};
117
};
118
119
module.exports = CancelToken;
120
121