Last active
June 13, 2019 14:50
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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