4

I know my code has the correct logic, but everywhere I look I'm told not to use nested promises. Is this a use case for nested promises?

The logic is as follows:

  • promise1 fails -> reverse promise1

  • promise1 succeeds -> promise2/promise3 fails -> reverse promise1, promise2, promise 3

  • promise1 succeeds -> promise2 & promise3 succeeds

    let data = null;
    promise1.then((response) => {
        data = response;
        return Promise.all([promise2(), proimse3()])
            .catch((error) => {
                //Reverse only promise2, promise3
                //Throw error to reverse promise1
            });
    }).then((id) => {
        something(data);
    }).catch((error) => {
        //Reverse only promise1
    });
    
Eric Larson
  • 509
  • 3
  • 14
  • 2
    This is somewhat opinionated, but there's nothing wrong with nesting promises. Like functions, you just have to be careful not to nest too greedily or too deep. – ssube Jul 12 '17 at 03:11
  • 1
    _"but everywhere I look I'm told not to use nested promises."_ Can you share links to the resources that you are referencing? – guest271314 Jul 12 '17 at 03:18
  • You're looking in the wrong places. [Nesting promises is fine where appropriate](https://stackoverflow.com/search?q=user%3Ame%20nesting%20promises), and that `catch` inside the `then` definitely is appropriate. – Bergi Jul 12 '17 at 03:50
  • Regarding that `data` variable though, see [How do I access previous promise results in a `.then()` chain?](https://stackoverflow.com/q/28250680/1048572). (Hint: [Nesting could help](https://stackoverflow.com/a/28250687/1048572) here as well :-)) – Bergi Jul 12 '17 at 03:51

0 Answers0