import { $timeout } from 'ngimport'; export interface IRetryablePromise { cancel: () => void; promise: PromiseLike; } export const retryablePromise = ( closure: () => PromiseLike, interval = 1000, maxTries = 0, ): IRetryablePromise => { let currentTimeout: PromiseLike; let currentTries = 0; const retryPromise: () => PromiseLike = () => { currentTries++; if (maxTries === 0 || currentTries <= maxTries) { return closure().catch(() => { currentTimeout = $timeout(retryPromise, interval); return currentTimeout; }); } else { return closure(); } }; const promise = retryPromise(); const cancel = () => { if (currentTimeout) { $timeout.cancel(currentTimeout); } }; return { promise, cancel }; };