Last active
October 25, 2021 13:35
-
-
Save ahmed-musallam/3f36751fdfddbb868559cb29eeaa27ad to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// poll async featch calls in a syncronized fashion, IE do not start the next function call until the previous was resolved. | |
// also allows for throttling :) | |
async function poll(fn, onData, throttle) { | |
const _throttle = throttle || 5000; | |
let lastPollStarted; | |
async function _poll(_fn, _onData) { | |
lastPollStarted = new Date().getTime(); | |
let response = await _fn(); | |
if (response.status === 200) { | |
// Get and show the message | |
var stopPolling = onData(response); | |
if (stopPolling) { | |
return; | |
} | |
const lastPollFinished = new Date().getTime(); | |
const elapsed = lastPollFinished - lastPollStarted; | |
if (elapsed < _throttle) { | |
await new Promise(resolve => setTimeout(resolve, _throttle - elapsed)); | |
} | |
// Call subscribe() again to get the next message | |
await _poll(_fn, _onData); | |
} | |
else { | |
console.error("Got non-200 response while polling: ", response); | |
} | |
} | |
_poll(fn, onData); | |
} | |
// USAGE | |
async function getGoogle() { | |
const googleResponse = await fetch("/") | |
return googleResponse; | |
} | |
poll(getGoogle, (response) => console.log(response)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment