import { $q, $timeout } from 'ngimport'; export class RetryService { // interval is in milliseconds public static buildRetrySequence( func: () => T | PromiseLike, stopCondition: (results: T) => boolean, limit: number, interval: number, ): PromiseLike { const call: T | PromiseLike = func(); const promise: PromiseLike = call.hasOwnProperty('then') ? (call as PromiseLike) : $q.resolve(call); if (limit === 0) { return promise; } else { return promise .then((result: T) => { if (stopCondition(result)) { return result; } else { return $timeout(interval).then(() => this.buildRetrySequence(func, stopCondition, limit - 1, interval)); } }) .catch(() => $timeout(interval).then(() => this.buildRetrySequence(func, stopCondition, limit - 1, interval))); } } }