forked from wenfangdu/pause-poll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
51 lines (44 loc) · 1.03 KB
/
main.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* @param {number} [ms]
* @param {Function} [cb]
* @param {any[]} args
*
* @returns {Promise<any>}
*/
export const pause = (ms, cb, ...args) => {
let timeout
const promise = new Promise((resolve, reject) => {
timeout = setTimeout(async () => {
try {
resolve(await cb?.(...args))
} catch (error) {
reject(error)
}
}, ms)
})
promise.abort = () => clearTimeout(timeout)
return promise
}
/**
* @param {number} [interval]
* @param {number} [times]
* @param {Function} [cb]
* @param {any[]} args
*
* @returns {Promise<any>}
*/
export const poll = async (interval, times, cb, ...args) => {
let result
const resolve = value => (times = 0) || (result = value)
const reject = reason => (times = 0) || (result = Promise.reject(reason))
await (async function basePoll() {
if (times > 0) {
const _result = await cb(...args, resolve, reject)
if (times) {
result = _result
--times && (await pause(interval, basePoll))
}
}
})()
return result
}