干净的代码和嵌套的承诺

Clean code and Nested promises

本文关键字:嵌套 承诺 代码      更新时间:2023-09-26

使用嵌套promise编写干净代码的正确策略是什么?使用promise背后的一个想法是去掉嵌套回调(也称为callback hell)。即使在使用promise时,嵌套有时似乎也是不可避免的:

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
        })
     })
  }) 

有没有一种方法可以摆脱嵌套,使代码更加"线性"。事实上,这段代码看起来与使用回调的代码没有太大区别。

使用promise的最大优势是链接。这就是你应该如何正确使用它:

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
})

每次在.then内部返回Promise时,它都被用作下一个.then回调的Promise。