Guest User

Untitled

a guest
Feb 21st, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. /**
  2. * Asynchronously retry a given task the given times, but as least as long as the task does not
  3. * throw an error or returns the first time. The return value is a promise with the value
  4. * of the rejected/resolved task.
  5. */
  6. export const retryAsync = (times, task) => {
  7. if (!task || typeof task !== 'function' || times < 0) {
  8. throw new TypeError(
  9. 'No task passed or task is not of type function or times is a negative value.'
  10. );
  11. }
  12.  
  13. return new Promise(async (resolve, reject) => {
  14. for (let i = 0; i < times; i++) {
  15. try {
  16. const result = await task();
  17. resolve(result);
  18. break;
  19. } catch (error) {
  20. if (i === times - 1) {
  21. reject(error);
  22. }
  23. }
  24. }
  25. });
  26. };
Add Comment
Please, Sign In to add comment