Search code examples
javascriptes6-promise

Passing through values with nested then statements


I have a function which has the following format:

this.callPromiseFunction1(params)
.then(results1 => {
    if (results1.length > 2) {
        this.callPromiseFunction2(params)
        .then(results2 => {
            return results2.stuff;
        }).catch(reject);
    } else {
        return results1.stuff;
    }
})
.then(results3 => {
    this.callPromiseFunction3(someotherparams)
    //do stuff
}).catch(reject)

My issue is that if I enter the conditional and call a promise within the first then() statement, I get a timing issue and results3 is undefined. Results3 is defined if I enter the else statement of the first then() statement.

How do I fix this timing issue and allow nested then() statements and promises without completely rewriting my promises and forcing them to work together? Is there a way to force the promise to complete in the then statement before continuing to the next then()?


Solution

  • You can fix that problem by returning the promise. If you notice, in the case in which the if statement of your code executes, you don't return anything. Returning the promise will cause it to get inserted before the next link in the promise chain. Also, you don't need the catch on that since the last catch at the very end will handle that. Also it's a nice idea to do an early return. This is what your code could look like:

    this.callPromiseFunction1(params)
      .then(results1 => {
        if(results1.length <= 2) return results1.stuff;
        return this.callPromiseFunction2(params)
          .then(results2 => results2.stuff);
      })
      .then(results3 => {
        this.callPromiseFunction3(someotherparams)
        //do stuff
      })
      .catch(reject);