Created
January 15, 2023 18:59
-
-
Save perjo927/daac58252bfc8099cede3c124bdf44fb to your computer and use it in GitHub Desktop.
Async polling generator function with stop condition
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 wait = (time) => { | |
return new Promise((resolve) => { | |
setTimeout(resolve, time); | |
}); | |
}; | |
// Fake polling data | |
const fakeData = [null, null, null, { data: { foo: 'bar' } }]; | |
let i = 0; | |
// Fake fetch of real time data | |
async function fakeFetch(url) { | |
if (i === fakeData.length) i = 0; | |
const currentData = fakeData[i++]; | |
return currentData; | |
} | |
// Function that calls an endpoint repeatedly and yields the result | |
// for a duration of "max" ms in intervals of "interval" ms | |
async function* createPoller({ url, max = 10000, interval = 500 }) { | |
for (let time = 0; time <= max; time += interval) { | |
const data = await fakeFetch(url); | |
yield data; | |
await wait(interval); | |
} | |
} | |
// Consumes the poller generator and stops | |
// when the "isDone" callback returns true, with data | |
async function runPollerUntilDone({ poller, isDone }) { | |
for await (const data of poller) { | |
if (isDone(data)) { | |
return data; | |
} | |
} | |
return null; | |
} | |
// Create poller | |
const dataPoller = createPoller({ | |
max: 5000, | |
interval: 500, | |
}); | |
// Execute the poller and stop when data is found | |
const data = await runPollerUntilDone({ | |
poller: dataPoller, | |
isDone: (_data) => Boolean(_data), | |
}); | |
console.log(data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment