Last active
August 31, 2022 14:32
-
-
Save brunogarcia/fe4f223500246c1268ff7eec0f767ad1 to your computer and use it in GitHub Desktop.
Polling implementation in Typescript
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
type Fn<T> = (payload: any) => T | |
type PromiseFn<T> = () => Promise<T> | |
type Options = { | |
maxAttempts?: number, | |
timeout?: number, | |
delta?: number, | |
validate?: Fn<boolean> | null, | |
} | |
/** | |
* Polling implementation in Typescript | |
* @param {PromiseFn} callback - The callback to execute | |
* @param {Options} options - The options to configure the polling | |
* @returns Promise<any> | |
* @link {https://levelup.gitconnected.com/polling-in-javascript-ab2d6378705a} | |
*/ | |
async function polling (callback: PromiseFn<any>, options: Options): Promise<any> { | |
let attempts = 0 | |
const { maxAttempts = 10, timeout = 1000, delta = 1, validate = null } = options | |
const executePoll = async (resolve: Fn<void>, reject: Fn<void>, ms = timeout) => { | |
const result: any = await callback() | |
const shouldResolve = validate?.(result) | |
const maxAttemptsReached = attempts === maxAttempts | |
attempts++ | |
if (shouldResolve) { | |
return resolve(result) | |
} else if (maxAttemptsReached) { | |
if (!validate) { | |
return resolve(result) | |
} else { | |
return reject(new Error('Exceeded max attempts')) | |
} | |
} else { | |
setTimeout(executePoll, ms, resolve, reject, ms * delta) | |
} | |
} | |
return new Promise(executePoll) | |
} | |
/** | |
* Example | |
* Get 3 jokes from the API of Chuck Norris | |
*/ | |
async function getChuckNorrisJokes() { | |
const jokes: any[] = [] | |
try { | |
await polling( | |
async () => { | |
const { value } = await | |
fetch("https://api.chucknorris.io/jokes/random") | |
.then(response => response.json()) | |
jokes.push(value) | |
}, | |
{ maxAttempts: 3, timeout: 1000, delta: 1, validate: null } | |
) | |
} catch(error) { | |
console.log(error) | |
} finally { | |
// Should display after 3 seconds: ["joke 1...", "joke 2...", "joke 3..."] | |
console.log(jokes) | |
} | |
} | |
/** | |
* Execute the example | |
*/ | |
getChuckNorrisJokes() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment