promisePoll(
// a function that takes no param and return a promise
// `.bind(...)` as much a you want!
() => { return aPromise; },
// a function that will be called with the resolved value
// of return value of the first function
// and that should return true if the condition is satisfied
(res) => { return res.prop = 'expectedValue'; },
// wait: number of milliseconds between 2 function1 calls
500,
// failAfter: number of milliseconds between 2 function1 calls
3000);
Gotcha
- We do not garantee that this function will take a most
failAfter
ms: if the condition is never satisfied andfailAfter
is not a multiple ofwait
, then the returned promise might fail afterMath.ceil(failAfter / wait) * wait
( which is> failAfter
)
This will resolve after ~600ms:
let a = 1;
setTimeout(() => { a = 2; }, 500);
return promisePoll(
function () { return Promise.resolve(a); },
(res) => res === 2,
200,
1000
);
This is rejected after ~1000ms, even if failedAfter
is 900
:
let a = 1;
setTimeout(() => { a = 2; }, 5000);
return promisePoll(
function () { return Promise.resolve(a); },
(res) => res === 2,
200,
900
);