清洁代码和嵌套承诺

时间:2016-04-28 13:59:37

标签: javascript node.js asynchronous ecmascript-6 es6-promise

使用嵌套承诺编写干净代码的正确策略是什么?使用promises背后的一个想法是摆脱嵌套的回调,即callback hell。即使使用承诺,嵌套似乎有时也是不可避免的:

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

有没有办法摆脱嵌套并使代码更“线性”。实际上,此代码与使用回调的代码看起来并没有太大差别。

1 个答案:

答案 0 :(得分:4)

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

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回调的承诺。

相关问题