Search code examples
javascriptecmascript-6es6-promise

Retry promise until resolved (Too much recursion error)


I was trying to test if I could have a promise retry until it resolved, but it keeps giving "too much recursion" error and I can't understand why it doesn't stop after the 3rd recursion.

The following code is trying to emulate a failed query request to a server, which comes from a non-promise function.

function nonPromiseCallback(x, resolve, reject){    
  if(x < 3){
    reject(x)
  }else{
    resolve(x)
  }
}

function tryUntilThree(x){
  return new Promise( (resolve, reject) => {
    nonPromiseCallback(x, resolve, tryUntilThree(x+1));
  })
}

tryUntilThree(1)
.then(console.log);

Solution

  • Since you are interested in a promise failure, you could use the catch handler.

    As to why your code doesn't work, heres a good explaination by some (also in the comment):

    You get too much recursion because tryUntilThree is called too many times. Notice that you have written tryUntilThree(x+1), ie the engine has to resolve the call to tryUntilThree before it can call nonPromiseCallback. You have an infinite loop there.

    function nonPromiseCallback(x, resolve, reject){    
      if(x < 3){
        reject(x)
      }else{
        resolve(x)
      }
    }
    
    function tryUntilThree(x){
      return new Promise( (resolve, reject) => 
        nonPromiseCallback(x, resolve, reject)
      ).catch(() => 
        tryUntilThree(x + 1)
      )
    }
    
    tryUntilThree(1)
    .then(console.log);