!97 [inual-request]<feat> 优化取消请求体验

Merge pull request !97 from 涂旭辉/master
This commit is contained in:
openInula-robot 2023-12-05 11:58:51 +00:00 committed by Gitee
commit 6383627ab6
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 25 additions and 3 deletions

View File

@ -168,8 +168,14 @@ export const fetchRequest = (config: IrRequestConfig): Promise<IrResponse> => {
}
})
.catch((error: IrError) => {
// fetch 在取消请求的极限场景会抛出 Failed to fetch 的 error此时将其转为取消 error
if (signal?.aborted) {
const irError = new CancelError('request canceled', config);
reject(irError);
} else {
const irError = new IrError(error.message, 'ERR_FETCH_FAILED', responseData.config, responseData.request, responseData);
reject(irError);
}
});
})
.catch((error: IrError) => {

View File

@ -15,6 +15,7 @@
import { IrProgressEvent, IrRequestConfig, IrResponse } from '../types/interfaces';
import IrError from '../core/IrError';
import CancelError from '../cancel/CancelError';
function processUploadProgress(
onUploadProgress: (progressEvent: IrProgressEvent) => void | null,
@ -95,7 +96,7 @@ function processUploadProgress(
xhr.abort();
const errorMsg = config.timeoutErrorMessage ?? `timeout of ${config.timeout}ms exceeded`;
throw new IrError(errorMsg, '', config, xhr, undefined);
}
};
}
for (const header in config.headers) {
@ -106,6 +107,21 @@ function processUploadProgress(
xhr.setRequestHeader(header, config.headers[header]);
}
}
if (config.signal) {
const onCanceled = () => {
const irError = new CancelError('request canceled', config);
reject(irError);
xhr.abort();
};
if (config.signal.aborted) {
onCanceled();
} else {
config.signal.addEventListener('abort', onCanceled);
}
}
xhr.send(data);
};