Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active June 13, 2019 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfet97/d4693d73c64ffb8d38c51c2bea5a42e0 to your computer and use it in GitHub Desktop.
Save jfet97/d4693d73c64ffb8d38c51c2bea5a42e0 to your computer and use it in GitHub Desktop.
Utility function to endlessy perform an async action until it returns a non null/undefined value. A max timeout could be setted as well as an interval to separate the consectutive calls to the async action, and the process is cancelable.
const asyncCancelablePolling = function() {
const delay = (ms, val = ms) => new Promise(ok => setTimeout(ok, ms, val));
return function(action = async () => false, timeout = 10000, interval = 1000) {
let doPolling = true;
return {
result: Promise.race([
(async () => {
let res = null;
while (true && doPolling) {
try {
res = await action();
} catch {}
if (res != null) break;
await delay(interval);
}
return res;
})(),
delay(timeout, null).then(N => (doPolling = false, N).then(N => throw N)),
]),
cancel: () => {
doPolling = false;
}
}
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment