Skip to content

Instantly share code, notes, and snippets.

@perjo927
Created January 15, 2023 19:09
Show Gist options
  • Save perjo927/b21cb17eacb607d2a291dd51b5f7764d to your computer and use it in GitHub Desktop.
Save perjo927/b21cb17eacb607d2a291dd51b5f7764d to your computer and use it in GitHub Desktop.
Async polling generator for streams
// Wait utility
const wait = (timeInMs) => {
return new Promise((resolve) => {
setTimeout(resolve, timeInMs);
});
};
let i = 0;
// Fake real time data stream
const fakeLeaderboardData = [
['Per', 'Johan', 'Gunnar'],
['Anders', 'Sven', 'Ture'],
['Lars', 'Olof'],
['Göran', 'Agneta', 'Sigurd'],
['Lena'],
];
// Fake fetch of real time data
async function fakeFetch(url) {
if (i === fakeLeaderboardData.length) i = 0;
const currentLeaderBoard = fakeLeaderboardData[i++];
return currentLeaderBoard;
}
// Async poller generator that waits for a max amount of ms
// and yields an iterated value for every interval, in ms
async function* getPoller({ url, max, interval }) {
for (let time = 0; time <= max; time += interval) {
const leaders = await fakeFetch(url);
yield* leaders;
await wait(interval);
}
}
let pos = 1;
const poller = getPoller({
url: 'https://fake-api.com/leaderboard',
max: 1000,
interval: 500,
});
for await (const value of poller) {
console.log(`Position: ${pos++}. Name: ${value}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment