Last active
April 19, 2018 13:01
-
-
Save elsangedy/72bdda50b8bf5c523a450db834ba8829 to your computer and use it in GitHub Desktop.
Recursive function to execute function until attempts finish or promise resolve
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const waitFor = (delay = 0) => new Promise((resolve) => setTimeout(resolve, delay)) | |
const recursiveToZero = (func, attempt, delay, error) => { | |
if (attempt === 0) { | |
throw error || new Error('Fail') | |
} | |
return func().catch((err) => waitFor(delay).then(() => recursiveToZero(func, attempt - 1, delay, err))) | |
} | |
export const recursive = (func, attempts = 5, delay = 0) => Promise.resolve().then(() => recursiveToZero(func, attempts, delay)) | |
/** | |
* how to use | |
*/ | |
const myFunc = () => new Promise((resolve, reject) => { | |
const num = Math.floor(Math.random() * 10) + 1 | |
if (num % 2 === 0) { | |
resolve() | |
} else { | |
reject() | |
} | |
}) | |
recursive(myFunc, 3, 3000) | |
.then(() => console.log('success')) | |
.catch(() => console.log('error')) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const waitFor = (delay: number = 0): Promise<any> => new Promise((resolve) => setTimeout(resolve, delay)) | |
const recursiveToZero = (func: () => Promise<any>, attempt: number, delay: number, error?: any): Promise<any> => { | |
if (attempt === 0) { | |
throw error || new Error('Fail') | |
} | |
return func().catch((err) => waitFor(delay).then(() => recursiveToZero(func, attempt - 1, delay, err))) | |
} | |
export const recursive = (func: () => Promise<any>, attempts: number = 5, delay: number = 0) => Promise.resolve().then(() => recursiveToZero(func, attempts, delay)) | |
/** | |
* how to use | |
*/ | |
const myFunc = (): Promise<any> => new Promise((resolve, reject) => { | |
const num = Math.floor(Math.random() * 10) + 1 | |
if (num % 2 === 0) { | |
resolve() | |
} else { | |
reject() | |
} | |
}) | |
recursive(myFunc, 3, 3000) | |
.then(() => console.log('success')) | |
.catch(() => console.log('error')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment