如何取消未完成的请求?
代码:
// 取消请求:传入一个执行器函数
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
// 定义一个promise
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve; // 保存并向外抛出 外部也可以用
});
// 保存当前 token 对象
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 Cancel(message) {
this.message = message;
}
在 adapter 中也会有取消判断~
描述: