0

I'm trying to test a method for retrying failed async functions in javascript.

Following the example from https://stackoverflow.com/a/31630063/3094668, I made a JSFiddle http://jsfiddle.net/tdb3sa8k/19/

function doAsync(i) {
  console.log("doAsync " + i);
  return Promise.resolve();
}

function ayncFunc() {
  return doAsync(-1).catch(doAsync(0)).catch(doAsync(1)).catch(doAsync(2));
};

var retries = 3;

function ayncFunc2() {
  var p = doAsync(-1);

  for (var i=0; i < retries; i++) {
    p = p.catch(doAsync(i));
  }
  return p;
};

function ayncFunc3() {
  function recurse(i) {
    return doAsync(i).catch(function(e) {
      if (i < retries) {
        return recurse(++i);
      }
      throw e;
    });
  }
  return recurse(0);
};


 ayncFunc().catch(function(e) { console.log(e); })
.then(ayncFunc2).catch(function(e) { console.log(e); })
.then(ayncFunc3).catch(function(e) { console.log(e); });

The problem I have is that despite the doAsync function returning a resolved promise, the code falls in the catch block and the retries are performed.

Please not that in the code there are 3 methods for the retry mechanism. (ayncFunc, ayncFunc2 and ayncFunc3). ayncFunc3 seems to work, but the two former two give unexpected results. (doAsync should only run once).

The output now is

doAsync -1 doAsync 0 doAsync 1 doAsync 2

doAsync -1 doAsync 0 doAsync 1 doAsync 2

doAsync 0

Any help or insight would be greatly appreciated!

bluedot
  • 628
  • 8
  • 24
  • you cant chain catch blocks in a promise chain unless you throw from within catch https://www.peterbe.com/plog/chainable-catches-in-a-promise – Joe Warner Aug 24 '18 at 12:38

1 Answers1

2

You want to pass a function that is executed on catch, but you actually execute the function immeadiately and pass the resulting promise instead:

  p = p.catch(doAsync(i));

must be:

 p = p.catch(() => doAsync(i));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Thank you! I was too focused on the promise part, which is new to me and totaly missed this mistake. – bluedot Aug 24 '18 at 13:38