-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathindex.js
More file actions
95 lines (77 loc) · 2.36 KB
/
Copy pathindex.js
File metadata and controls
95 lines (77 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
export class TimeoutError extends Error {
name = 'TimeoutError';
constructor(message, options) {
super(message, options);
Error.captureStackTrace?.(this, TimeoutError);
}
}
const getAbortedReason = signal => signal.reason ?? new DOMException('This operation was aborted.', 'AbortError');
export default function pTimeout(promise, options) {
const {
milliseconds,
fallback,
message,
customTimers = {setTimeout, clearTimeout},
signal,
} = options;
let timer;
let abortHandler;
const wrappedPromise = new Promise((resolve, reject) => {
if (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {
throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
}
if (signal?.aborted) {
reject(getAbortedReason(signal));
return;
}
if (signal) {
abortHandler = () => {
reject(getAbortedReason(signal));
};
signal.addEventListener('abort', abortHandler, {once: true});
}
// Use .then() instead of async IIFE to preserve stack traces
// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-catch
promise.then(resolve, reject);
if (milliseconds === Number.POSITIVE_INFINITY) {
return;
}
// We create the error outside of `setTimeout` to preserve the stack trace.
const timeoutError = new TimeoutError();
// `.call(undefined, ...)` is needed for custom timers to avoid context issues
timer = customTimers.setTimeout.call(undefined, () => {
if (fallback) {
try {
resolve(fallback());
} catch (error) {
reject(error);
}
return;
}
if (typeof promise.cancel === 'function') {
promise.cancel();
}
if (message === false) {
resolve();
} else if (message instanceof Error) {
reject(message);
} else {
timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
reject(timeoutError);
}
}, milliseconds);
});
// eslint-disable-next-line promise/prefer-await-to-then
const cancelablePromise = wrappedPromise.finally(() => {
cancelablePromise.clear();
if (abortHandler && signal) {
signal.removeEventListener('abort', abortHandler);
}
});
cancelablePromise.clear = () => {
// `.call(undefined, ...)` is needed for custom timers to avoid context issues
customTimers.clearTimeout.call(undefined, timer);
timer = undefined;
};
return cancelablePromise;
}