Last active
August 17, 2021 20:52
-
-
Save karol-majewski/9d2c37ee751484599d8b08b580616e08 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
interface Options { | |
/** | |
* @default Infinity | |
*/ | |
maximumAttempts?: number; | |
/** | |
* @default 0 | |
*/ | |
timeoutMs?: number | |
} | |
const defaults: Required<Options> = { | |
maximumAttempts: Infinity, | |
timeoutMs: 0, | |
} | |
const sleep = async (ms: number): Promise<void> => new Promise<void>((resolve) => setTimeout(resolve, ms)); | |
const retry = ({ maximumAttempts, timeoutMs } = { | |
maximumAttempts: Infinity, | |
timeoutMs: 0, | |
}) => <T,>(thunk: () => Promise<T>): () => Promise<T> => { | |
let attempts = 0; | |
let startDate = Date.now(); | |
const attempt = async (): Promise<T> => { | |
attempts++; | |
let result: T; | |
try { | |
result = await thunk(); | |
} catch(error) { | |
const endDate = Date.now(); | |
if (attempts === maximumAttempts || (timeoutMs > 0 && (endDate - timeoutMs) > startDate )) { | |
throw error; | |
} | |
result = await attempt() | |
} | |
return result; | |
} | |
return attempt; | |
} | |
const waitForEvent = retry({ maximumAttempts: 10, timeoutMs: 10000 })(() => { | |
return new Promise<boolean>(async (resolve, reject) => { | |
await sleep(1000); | |
if (Math.random() < 0.2) { | |
console.log('Done! We made it!') | |
resolve(true) | |
} else { | |
console.log('Nah, not ready yet.'); | |
reject(false) | |
} | |
}) | |
}) | |
Promise.resolve().then(() => { | |
}).then(async () => { | |
console.time('Total time spent awaiting the state') | |
await waitForEvent(); | |
console.timeEnd('Total time spent awaiting the state') | |
}) |
interface Options {
/**
* @default Infinity
*/
maximumAttempts: number;
/**
* @default 0
*/
timeoutMs: number;
}
export const retry = (options?: Partial<Options> = {}) => <T,>(thunk: () => Promise<T>): (() => Promise<T>) => {
const { maximumAttempts = Infinity, timeoutMs = 0 } = options;
let attempts = 0;
const startDate = Date.now();
const attempt = async (): Promise<T> => {
attempts++;
let result: T;
try {
result = await thunk();
} catch (error) {
const endDate = Date.now();
if (attempts === maximumAttempts || (timeoutMs > 0 && endDate - timeoutMs > startDate)) {
throw error;
}
result = await attempt();
}
return result;
};
return attempt;
};
/**
* Asynchronous effect to retry.
*/
const fetchMyWebsite = () => fetch("https://website.rocks").then(response => response.body);
/**
* Create a factory with provided configuration.
*/
const createRetriableRequest = retry({ maximumAttempts: Infinity, timeoutMs: 3600 * 1000 });
/**
* Create a retriable effect with the same signature as the original function.
*/
const keepFetchingMyWebsite = createRetriableRequest(fetchMyWebsite)
/**
* Usage
*/
async () => {
await keepFetchingMyWebsite();
console.log('Finally done!')
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.typescriptlang.org/play?#code/MYewdgziA2CmB0w4EMBOAKAlAbgFC4EswAXWVAM2WFgAIB5AB2IPAhoG9caaB6AKj5dufGgAEAJrEoBXaMRoBJMOSIFiATyE0+PIQFtkADwJ7pegILFSephAD8ALhpgzAIzJ5u-Qd21jJMnI0AAxaOkLMerAg0sQAsvZOLnruqLgAvvigkPIByLLEEE4ASrAAjtIEqLDiADyMzKwAfDQAvBz6RiZmlta2TkoqYGrqADQRJtGxCU7B45m42RDyEHCwDG00yBDqYMA06HpFzm5kmE4ACqggegQQsLUAbiAE4i2tLWCwAO40Vzd3B7PV5NdDoapQaCPWCYNote7EAAqkxixHBsEh0NGNCOmBw+EWrHk1WIqHUm3Q7BxXVMFissBshWxkSm8TY6U2nG4BmMtN6DP6imUqg0424LNRMxC81hHxotURo1BxAAFtIwABrJxYOF-a63e4KprnA6ylr-A0PRHvFpcmhweTIemMtjtYKee2wFbENDEAAiTto7QDpHgYBA3yweCES0dzqYm22u32WEu+sBRt1du4Tr6hQA1PmPdwHTQIQUnIjo74aEsYAhoCAAOaUrbxwo0dL4rQ0Unk7O+ctBdrIb7INS9tWaqM9jnAJ3AFXoMjXVCwgfcWM0WBgcQhoM0fdhiMzmvcAjkA65gUd1p36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