Search code examples
javascriptpromisechaining

Correct chaining of a recursive javascript promise


I am trying to write a recursive function that calls itself a number of times before resolving with the correct value.

const recursivePromise = (val = 1) => {
  return new Promise((resolve, reject) => {
    if (val > 5) {
      resolve(val)
    } else {
     return recursivePromise(val + 1)
    }
  })
}

const doSomethingWithResult = (val) => {
  return new Promise((resolve, reject) => {
    resolve(val + 2)
  })
}

recursivePromise().then(doSomethingWithResult).then(value => console.log(value))

If I give a initial value '6', the promise will resolve correctly and the value passed to the second promise chained to it. However if the recursivePromise has to call itself one or more times, the resolve value will never reach the second element of the promise chain.

Could anyone point out what I'm missing here?


Solution

  • when you invoke new Promise(callback), the callback's return value is ignored. You have to call resolve explicitly to fulfill the promise, i.e

    const recursivePromise = (val = 1) => {
        return new Promise((resolve, reject) => {
            if (val > 5) {
                resolve(val)
            } else {
                recursivePromise(val + 1).then(resolve)
            }
        })
    }
    

    Better yet, rewrite it without new Promise:

    const recursivePromise = (val = 1) => {
        if (val > 5)
            return Promise.resolve(val)
        return recursivePromise(val + 1)
    }
    
    recursivePromise().then(console.log)