Add abortAfterTimeout() utility to make it easy to add timeouts
This commit is contained in:
parent
6ec4c09325
commit
9882f1c919
3 changed files with 28 additions and 0 deletions
|
|
@ -48,6 +48,8 @@ export type RequestOptions = {
|
|||
|
||||
/**
|
||||
* Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request().
|
||||
*
|
||||
* Use abortAfterTimeout() to easily implement timeouts using this signal.
|
||||
*/
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
|
|
|||
15
src/utils.test.ts
Normal file
15
src/utils.test.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { abortAfterTimeout } from "./utils.js";
|
||||
|
||||
describe("abortAfterTimeout", () => {
|
||||
it("should abort after timeout", () => {
|
||||
const signal = abortAfterTimeout(0);
|
||||
expect(signal.aborted).toBe(false);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
expect(signal.aborted).toBe(true);
|
||||
resolve(true);
|
||||
}, 0);
|
||||
});
|
||||
});
|
||||
});
|
||||
11
src/utils.ts
Normal file
11
src/utils.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
/**
|
||||
* Returns an AbortSignal that will enter aborted state after `timeoutMs` milliseconds.
|
||||
*/
|
||||
export function abortAfterTimeout(timeoutMs: number): AbortSignal {
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => {
|
||||
controller.abort();
|
||||
}, timeoutMs);
|
||||
|
||||
return controller.signal;
|
||||
}
|
||||
Loading…
Reference in a new issue