【问题标题】:How to use bluebird to chain consecutive callback functions such that they both have on catch block如何使用 bluebird 链接连续的回调函数,使它们都具有 catch 块
【发布时间】:2017-05-11 07:11:13
【问题描述】:

我有两个来自 mongoose 的回调函数,我想使用 bluebird 的 then 链接它们

我的第一个回调函数成功使用then

User.findOne().distinct(('Friends.id'), {id: req.body.myId}, {Friends: {$elemMatch: { gender: req.body.gender}}})
.then(function(IDs){

var results = //////some computation

})
.catch(function(error)) {


 } 

我只是无法正确链接第二个回调函数的语法,以便它共享第一个回调函数的 catch 方法。在这种情况下,我不能使用Promise.all,因为第二个回调函数依赖于第一个回调函数的results。无论如何,第二个回调函数如下:

  User.find({Friends: { $not: { $elemMatch: { id: req.body.myId }}}, id: {$in: results}}, function(err, users){



})

【问题讨论】:

    标签: node.js mongodb mongoose promise bluebird


    【解决方案1】:

    你可以像这样链接两个 Promise。

    User.findOne().distinct(('Friends.id'), {id: req.body.myId}, {Friends: {$elemMatch: { gender: req.body.gender}}})
        .then(function(IDs){
    
            var results = //////some computation
    
            // second promise
            return User.find({Friends: { $not: { $elemMatch: { id: req.body.myId }}}, id: {$in: results}})
        })
        .then(function(friends) {
            // do something with the result of the second query
        })
        .catch(function(error)) {
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-27
      • 2017-09-12
      • 2017-03-27
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      相关资源
      最近更新 更多