Created
January 27, 2016 09:18
-
-
Save YuMS/ffcaf6f53bed03137ecc to your computer and use it in GitHub Desktop.
generate a promise that keep invoking another promise generator until it succeed
This file contains 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
function retryUntilSuccess(promiseFunc, args, timeout = 1000, retry = -1) { | |
return new Promise((resolve, reject) => { | |
const tryForTimes = (attempts) => { | |
promiseFunc(...args).then((result) => { | |
resolve(result); | |
}).catch((err) => { | |
if (attempts === 0) { | |
reject(err); | |
} else { | |
setTimeout(() => tryForTimes(attempts - 1), timeout); | |
} | |
}); | |
}; | |
tryForTimes(retry); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment