-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
34 lines (32 loc) · 991 Bytes
/
index.js
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
async function awaitdelay(promise, { timeout }) {
// Check if timeout is a positive number
if (typeof timeout !== 'number' || Math.sign(timeout) !== 1) {
throw new Error('Timeout should be a positive number');
}
let timer;
try {
return await Promise.race([
promise,
new Promise((_, reject) =>
timer = setTimeout(() =>
reject(new Error(`The promise did not resolve within ${timeout} milliseconds.`)),
timeout)
)
]);
} catch (error) {
if (error instanceof Error) {
throw error; // re-throw the error
} else {
throw new Error(error); // create a new Error instance with the string
}
} finally {
clearTimeout(timer);
}
}
// Node.js module exports
if (typeof module !== 'undefined' && module.exports) {
module.exports = awaitdelay;
} else {
// ESM
self.awaitdelay = awaitdelay;
}