corgi/src/utils/promise.util.ts

48 lines
1.2 KiB
TypeScript

/**
*
* @param {Function} cb
* @param {number} maxRetries
* @param {any[]} errorWhiteList
* @param {number} retries
* @return {Promise<T>}
*/
export function retry<T = any>(cb: Function, maxRetries: number = 3, errorWhiteList: any[] = [], retries: number = 0) {
return new Promise<T>((resolve, reject) => {
cb()
.then(resolve)
.catch(e => {
if (errorWhiteList.indexOf(e.constructor) !== -1 && retries++ < maxRetries) {
setTimeout(() => {
retry<T>(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<T = any> {
public promise: Promise<T>
public resolve: Function
public reject: Function
constructor() {
this.promise = new Promise<T>((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)
}
}