Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Asynchronously retry a given task the given times, but as least as long as the task does not
- * throw an error or returns the first time. The return value is a promise with the value
- * of the rejected/resolved task.
- */
- export const retryAsync = (times, task) => {
- if (!task || typeof task !== 'function' || times < 0) {
- throw new TypeError(
- 'No task passed or task is not of type function or times is a negative value.'
- );
- }
- return new Promise(async (resolve, reject) => {
- for (let i = 0; i < times; i++) {
- try {
- const result = await task();
- resolve(result);
- break;
- } catch (error) {
- if (i === times - 1) {
- reject(error);
- }
- }
- }
- });
- };
Add Comment
Please, Sign In to add comment