Last active
October 13, 2021 08:56
-
-
Save ungarson/b5060a9a46237da01c5f649ec3e7bb92 to your computer and use it in GitHub Desktop.
Try asynchronous function several times until it returns result
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
async function tryAsyncUntilOk(func, times = 4, timeout = 1250) { | |
function delay(ms) { | |
return new Promise(resolve => setTimeout(resolve, ms)); | |
} | |
for (let i = 0; i < times; i++) { | |
try { | |
const res = await func(); | |
if (typeof res !== "undefined") { | |
return res; | |
} else { | |
await delay(timeout); | |
} | |
} catch (e) { | |
if (i === times - 1) { | |
throw e; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test function:
Call it: