Skip to content

Instantly share code, notes, and snippets.

@ungarson
Last active October 13, 2021 08:56
Show Gist options
  • Save ungarson/b5060a9a46237da01c5f649ec3e7bb92 to your computer and use it in GitHub Desktop.
Save ungarson/b5060a9a46237da01c5f649ec3e7bb92 to your computer and use it in GitHub Desktop.
Try asynchronous function several times until it returns result
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;
}
}
}
}
@ungarson
Copy link
Author

ungarson commented Oct 13, 2021

Test function:

let tryCount = 0;
function delayWithError(t, v) {
   return new Promise(function(resolve) { 
        if (tryCount === 0) {
           ++tryCount;
           throw new Error('Yooouuhooo');
        } else {
            ++tryCount;
            setTimeout(resolve.bind(null, v), t)
        }
   });
}

Call it:

const res = await tryAsyncUntilOk(() => delayWithError(2000, 30));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment