一、步骤
(1) 创建了一个控制器 controller,每个控制器都自带一个信号对象(signal 属性)
(2)发送请求的时候把这个信号对象带上(signal 参数)
(3)通过控制器的 abort() 方法,中断请求。
二、事例
(1)upload函数签名
/** @name 上传到OSS */
upload = async (
file: File,
path: string,
observe?: (ob: FetchObserver) => void,
signal?: AbortSignal,
)
(2)创建AbortController对象,调用upload请求并传入signal
async handleUpload({ file }: UploadOption) {
const controller = new AbortController();
const signal = controller.signal;
const ossPath = await this.computedService
.upload(
file,
this.computedUploadPath,
ob =>
ob.addEventListener('requestprogress', event => {
const percentage = (event.loaded / event.total) * 100;
const status = percentage >= 100 ? 'finished' : 'uploading';
this.$emit(
'uploadChange',
this.getUploadData(uploadData, percentage, status),
);
}),
signal,
)
}
(3)中断请求
/** @name 取消上传 */
handleCancelUpload({ controller, file }: FileItem) {
if (controller) {
controller.abort();
}
}
三、参考
https://developer.mozilla.org/zh-CN/docs/Web/API/AbortController