-
-
Save shakahl/863c8850d277c2fcef4a42d90fa00c5c to your computer and use it in GitHub Desktop.
Code retry with promises
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
| // Author: Renat Tuktarov ([email protected]) | |
| const retry = function(fn, prev) { | |
| return new Promise((current, reject) => { | |
| const resolve = _ => (prev && prev()) || current(); | |
| fn(resolve, delay => { | |
| setTimeout(_ => { | |
| retry(fn, resolve); | |
| }, delay); | |
| }); | |
| }); | |
| }; | |
| function run() { | |
| let attempt = 1; | |
| retry((done, retry) => { | |
| console.log('attempt: ', attempt); | |
| if (attempt !== 3) { | |
| attempt += 1; | |
| retry(1000); | |
| } else { | |
| done(); | |
| } | |
| }); | |
| } | |
| run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment