通过AbortController取消请求2
我们在上一节中实现了xhr.js取消请求的逻辑,这一节我们实现dispatchRequest.js
中取消请求的部分。首先我们创建throwIfCancellationRequested
函数,该函数接收一个配置对象,通过该对象判断用户是否中止了请求,如果是,则抛出一个取消请求的错误。
var defaults = require("../defaults");
var transformData = require("./transformData");
var isCancel = require('../cancel/isCancel');
var CanceledError = require('../cancel/CanceledError');
function throwIfCancellationRequested(config) {
if (config.signal && config.signal.aborted) {
throw new CanceledError();
}
}
module.exports = function dispatchRequest(config) {
// 在adapter执行前,用户就中止请求
throwIfCancellationRequested(config);
// 确保 headers 存在
config.headers = config.headers || {};
// 省略中间部分代码,可以参考前面的内容或最后一章提供的源码资料
// ...
return adapter(config).then(
function onAdapterResolution(response) {
// 成功的响应还没返回前,用户终止了请求,则抛出取消错误
throwIfCancellationRequested(config);
// 转换响应数据
return response;
},
function onAdapterRejection(reason) {
if (!isCancel(reason)) {
// 如果reason不是CanceledError且请求失败的响应还没返回前,用户终止了请求,则抛出取消错误
throwIfCancellationRequested(config);
// 转换响应数据
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
}
);
};