-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise-poll.js
38 lines (36 loc) · 1.3 KB
/
promise-poll.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
/**
* promise-poll
* Poll an asynchronous operation that is itself a Promise.
* @author [email protected] https://github.com/jeff3dx/promise-poll
*
* @param {func} targetPromiseFn - Your function that returns a Promise. Resolve falsy to poll again or truthy to finish
* @param {Number} intervalMs - Idle wait time between polls
* @param {Number} timeoutMs - Polling quits after this duration. Won't interupt a poll in progress.
* @returns {Promise} - promisePoll returns a Promise that resolves when polling is done
*/
function promisePoll(PromiseFn, intervalMs, timeoutMs) {
var endTime = Date.now() + timeoutMs;
return new Promise(function(resolve, reject) {
_poll(targetPromiseFn, intervalMs, endTime, resolve);
});
}
function _poll(targetPromiseFn, intervalMs, endTime, resolve) {
var pollagain = _poll.bind(this, targetPromiseFn, intervalMs, endTime, resolve);
return targetPromiseFn()
.then(function(done) {
if (!!done) {
resolve(done);
} else if (Date.now() > endTime) {
console.log('promisePoll stopped polling on timeout');
resolve(null);
} else {
setTimeout(pollagain, intervalMs);
}
})
.catch(function(ex) {
throw new Error('Error within promisePoll:' + ex);
})
}
module.exports = {
promisePoll: promisePoll
};