import { APIResponseType } from "../types/APIResponseType";
export const RETRY_DEFAULT = 3; // 3 times
export const DELAY_IN_RETRY = 300; // 300 ms
// /**
// * @param promise A promise to resolve
// * @nthTry Number of tries before rejecting
// * @desc Retries a promise n no. of times before rejecting.
// * @returns resolved promise
// */
export async function retryPromise(promise: any, nthTry: number, delayTime: number): Promise<APIResponseType<any>>{
try {
const data = await promise;
return data;
} catch (e) {
if (nthTry === 1) {
return Promise.reject(e);
}
console.log('retrying', nthTry, 'time');
await waitFor(delayTime);
return retryPromise(promise, nthTry - 1, delayTime);
}
}
/**
* Util function to return a promise which is resolved in provided milliseconds
*/
export function waitFor(millSeconds: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(() => {
resolve();
}, millSeconds);
});
}
Source