3

What's the right strategy to using nested promises to write clean code? One of the ideas behind using promises is to get rid of nested callbacks aka callback hell. Even when using promises, nesting seems to be unavoidable sometimes:

User.find({hande: 'maxpane'})
  .then((user) => {
    Video.find({handle: user.handle})
     .then((videos) => {
       Comment.find({videoId: videos[0].id})
        .then((commentThead) => {
            //do some processing with commentThread, vidoes and user
        })
     })
  }) 

Is there a way to get rid of the nesting and make the code more "linear". As it is, this code doesn't look very different from code that uses callbacks.

Amal Antony
  • 6,477
  • 14
  • 53
  • 76
  • 2
    Seems like [this answer](http://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain) could be a good read for you, if not a duplicate. – CodingIntrigue Apr 28 '16 at 14:59

1 Answers1

4

The biggest advantage of using promises is chaining. That is how you should use it properly:

User.find({handle: 'maxpane'})
.then((user) => {
  return Video.find({handle: user.handle})
})
.then((videos) => {
  return Comment.find({videoId: videos[0].id})
})
.then((commentThead) => {
  //do some processing with commentThread, vidoes and user
})

Every time you return a Promise inside of .then it is used as a Promise for the next .then callback.

smnbbrv
  • 23,502
  • 9
  • 78
  • 109
  • 3
    Are `commentThread`, `videos` and `user` variables available in the final function, It appears to me that only commentThread is within the scope of the function. – Amal Antony Apr 28 '16 at 14:27