/** * * @param {Function} cb * @param {number} maxRetries * @param {any[]} errorWhiteList * @param {number} retries * @return {Promise} */ export function retry(cb: Function, maxRetries: number = 3, errorWhiteList: any[] = [], retries: number = 0) { return new Promise((resolve, reject) => { cb() .then(resolve) .catch(e => { if (errorWhiteList.indexOf(e.constructor) !== -1 && retries++ < maxRetries) { setTimeout(() => { retry(cb, maxRetries, errorWhiteList, retries) .then(resolve) .catch(e2 => reject(e2)) }, Math.floor(Math.random() * Math.pow(2, retries) * 400)) } else { reject(e) } }) }) } export class Deferred { public promise: Promise public resolve: Function public reject: Function constructor() { this.promise = new Promise((resolve, reject) => { this.resolve = resolve this.reject = reject }) } public then(func: (value: T) => any) { return this.promise.then.apply(this.promise, arguments) } public catch(func: (value: any) => any) { return this.promise.catch(func) } }