Recently, I came across this interesting class:
export class ExponentialBackoffUtils {
public static retry(promise: Promise<any>, maxRetries: number, onRetry?: Function) {
function waitFor(milliseconds: number) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
async function retryWithBackoff(retries: number) {
try {
if (retries > 0) {
const timeToWait = 2 ** retries * 1000;
await waitFor(timeToWait);
}
console.log('Retries: ', retries);
if (retries < 3) {
throw new Error();
}
return await promise();
} catch (e) {
if (retries < maxRetries) {
if (onRetry) {
onRetry();
}
return retryWithBackoff(retries + 1);
} else {
throw e;
}
}
}
return retryWithBackoff(0);
}
}
I encountered an issue where Typescript was yelling at me for trying to call the promise that I passed in...But why? It was complaining that promise has no call signatures.