面试官:如何中断已发出去的请求?
码农突围
共 7606字,需浏览 16分钟
·
2022-01-01 18:35
点击上方“码农突围”,马上关注
这里是码农充电第一站,回复“666”,获取一份专属大礼包 真爱,请设置“星标”或点个“在看 作者:紫圣 https://juejin.cn/post/7033906910583586829
推荐阅读:axios解析之cancelToken取消请求原理[2]
AbortController
AbortController():AbortController()构造函数创建一个新的 AbortController 对象实例
signal:signal 属性返回一个 AbortSignal 对象实例,它可以用来 with/about 一个Web(网络)请求
abort():终止一个尚未完成的Web(网络)请求,它能够终止 fetch 请求,任何响应Body的消费者和流
Fetch 中断请求
const controller = new AbortController();
let signal = controller.signal;
console.log('signal 的初始状态: ', signal);
const downloadBtn = document.querySelector('.download');
const abortBtn = document.querySelector('.abort');
downloadBtn.addEventListener('click', fetchVideo);
abortBtn.addEventListener('click', function() {
controller.abort();
console.log('signal 的中止状态: ', signal);
});
function fetchVideo() {
//...
fetch(url, {signal}).then(function(response) {
//...
}).catch(function(e) {
reports.textContent = 'Download error: ' + e.message;
})
}
复制代码
线上运行示例[4] (代码来源于MDN[5])
axios 中断请求
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('https://mdn.github.io/dom-examples/abort-api/sintel.mp4', {
cancelToken: source.token
}).catch(function (thrown) {
// 判断请求是否已中止
if (axios.isCancel(thrown)) {
// 参数 thrown 是自定义的信息
console.log('Request canceled', thrown.message);
} else {
// 处理错误
}
});
// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');
复制代码
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
})
});
// 取消请求
cancel('Operation canceled by the user.');
复制代码
线上运行示例[6] (代码来源于MDN[7])
umi-request 中断请求
umi 项目中使用 CancelToken 中止请求
import request from '@/utils/request';
const CancelToken = request.CancelToken;
let cancel: any;
// 合同文件上传 OSS
export async function uploadContractFileToOSS(postBody: Blob): Promise<any> {
return request(`/fms/ossUpload/financial_sys/contractFile`, {
method: "POST",
data: postBody,
requestType: 'form',
// 传递一个 executor 函数到 CancelToken 的构造函数来创建一个 cancel token
cancelToken: new CancelToken((c) => {
cancel = c
})
})
}
// 取消合同文件上传
export async function cancelUploadFile() {
return cancel && cancel()
}
复制代码
*uploadContractFileToOSS({ payload }: AnyAction, { call, put }: EffectsCommandMap): any {
const response = yield call(uploadContractFileToOSS, payload);
yield put({
type: 'save',
payload: {
uploadOSSResult: response?.data,
}
})
return response?.data
},
*cancelUploadFile(_: AnyAction, { call }: EffectsCommandMap): any {
const response = yield call(cancelUploadFile)
return response
},
复制代码
// 发起请求
dispatch({
type: 'contract/fetchContractFiles',
payload: {
contractId: `${id}`,
}
})
// 取消请求
dispatch({
type: "contract/cancelUploadFile"
})
复制代码
const errorHandler = (error: { response: Response }): Response => {
const { response } = error;
notification.destroy()
if (response && response.status) {
const errorText = codeMessage[response.status] || response.statusText;
const { status, url } = response;
notification.error({
message: `请求错误 ${status}: ${url}`,
description: errorText,
});
} else if (error?.['type'] === 'TypeError') {
notification.error({
description: '您的网络发生异常,无法连接服务器',
message: '网络异常',
});
} else if (error?.['request']?.['options']?.['cancelToken']) {
notification.warn({
description: '当前请求已被取消',
message: '取消请求',
});
} else if (!response) {
notification.error({
description: '您的网络发生异常,无法连接服务器',
message: '网络异常',
});
} else {
notification.error({
description: '请联系网站开发人员处理',
message: '未知错误',
});
}
return response;
};
复制代码
-End-
最近有一些小伙伴,让我帮忙找一些 面试题 资料,于是我翻遍了收藏的 5T 资料后,汇总整理出来,可以说是程序员面试必备!所有资料都整理到网盘了,欢迎下载!
点击👆卡片,关注后回复【面试题
】即可获取
评论