Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean code and Nested promises [duplicate]

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.

like image 778
Amal Antony Avatar asked Jul 16 '26 22:07

Amal Antony


1 Answers

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.

like image 119
smnbbrv Avatar answered Jul 18 '26 11:07

smnbbrv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!