Last active
October 21, 2020 19:30
-
-
Save antomor/eb35bb94065c1d6ec914ef5c1a20f829 to your computer and use it in GitHub Desktop.
Revisions
-
antomor revised this gist
Oct 21, 2020 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -37,7 +37,7 @@ const resolveAfterTimes = (times) => { const resolveAfter5Times = resolveAfterTimes(5); retry({ fn:resolveAfter5Times, maxRetries: 5, initialDelayMs: 200, intervalMs: 200 -
antomor revised this gist
Oct 21, 2020 . No changes.There are no files selected for viewing
-
antomor created this gist
Oct 21, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,57 @@ const wait = (milliSeconds) => { return new Promise((resolve) => setTimeout(() => resolve(), milliSeconds)); }; const retry = ({fn, maxRetries, initialDelayMs, intervalMs}) => { // first attempt after the initial delay let attempts = wait(initialDelayMs); if ( maxRetries > 0) { attempts = attempts.then(() => fn()); } // the attempts after the first will be executed after waiting for the milliseconds specified for (let i = 1; i < maxRetries; i++) { attempts = attempts.catch(() => wait(intervalMs).then(() => fn())); } attempts = attempts.catch(() => { throw new Error(`Failed retrying ${maxRetries} times`); }); return attempts; }; const hello = () => console.log("Hello"); // Simulate a number of attempts const resolveAfterTimes = (times) => { let index = 0; return () => { if (index >= times-1) { return Promise.resolve(); } index++; return Promise.reject(); } } // it resolves after 5 times const resolveAfter5Times = resolveAfterTimes(5); retry({ fn:resolveAfter, maxRetries: 5, initialDelayMs: 200, intervalMs: 200 }).then(() => hello()).catch((err) => console.error(err)); // or in async/await context try { await retry({ fn:resolveAfter, maxRetries: 5, initialDelayMs: 200, intervalMs: 200 }); hello(); } catch(error) { console.error(error); }