Files
jiapuapp/services/api/request-controller.js

32 lines
999 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const createRequestCancelledError = () => {
const error = new Error('请求已取消')
error.code = 'REQUEST_CANCELLED'
return error
}
// 页面只持有控制器,不依赖各端 RequestTask 的实现差异。
// 新请求会接管控制器;页面卸载时 abort() 会拒绝等待中的 Promise
// 避免已销毁页面继续处理成功回调。
export const createRequestController = () => {
let abortCurrent = null
return {
bind(abortRequest) {
if (typeof abortRequest !== 'function') throw new TypeError('请求中止器必须是函数')
if (abortCurrent) abortCurrent()
abortCurrent = abortRequest
},
release(abortRequest) {
if (abortCurrent === abortRequest) abortCurrent = null
},
abort() {
const abortRequest = abortCurrent
abortCurrent = null
if (abortRequest) abortRequest()
}
}
}
export const isRequestCancelled = (error) => error?.code === 'REQUEST_CANCELLED'
export { createRequestCancelledError }