在mongoose升级之后,async不会在回调中返回数据

时间:2017-01-27 12:48:25

标签: node.js mongodb asynchronous mongoose bluebird

在我的项目中,我使用async对数据库进行异步查询,我有这段代码:

async.auto({
        one: function(callback){
            getFriendsIds(userId, callback)
        },
        two: ['one', function(callback, results){
            getFriendsDetails(results.one, callback);
        }],
        final: ['one', 'two', function(callback, results) {
            res.status(200).send(results.two);
            return;
        }],
    }, function(err) {
        if (err) {
            sendError(res, err);
            return;
        }
    });

返回朋友的方法' ids看起来像这样:

function getFriendsIds(userId, callback) {
    var query = User.findOne({_id: userId});

    query.exec(function(err, user) {
        if(err) {
            callback(err);
            return;
        }

        return callback(null, user.friendsIds);
    });
}

完美无缺。该功能返回了朋友' ids和我在"两个"中使用它们。异步呼叫阻止。

mongoose4.3.7升级到4.7.8后,它停止了工作。我开始收到Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead警告,并且不再在回调中返回ID。

所以我将bluebird包添加到项目中并将其插入mongoose。现在警告消失了,但回调中仍未返回ID。

我还将async升级到最新版本,但它也没有帮助。

为了使这项工作,还有什么我应该做的吗?

1 个答案:

答案 0 :(得分:1)

使用promises的想法是不使用回调,并且您仍然在代码中使用回调。

假设你需要像蓝鸟一样

mongoose.Promise = require('bluebird');

现在你的功能应该是这样的:

function getFriendsIds(userId) {
    //This will now be a bluebird promise
    //that you can return
    return User.findOne({_id: userId}).exec()
        .then(function(user){
            //return the friendIds (this is wrapped in a promise and resolved)
            return user.friendsIds;
        });
}

函数的返回值将是user.friendsIds的数组。利用promises的链接可能性,您可以编写一个函数来获取每个朋友的详细信息,并将其作为friendDetails的数组返回。

function getFriendsDetails(friendIds) {
    //For each friendId in friendIds, get the details from another function
    //(Promise = require("bluebird") as well)
    return Promise.map(friendIds, function(friendId) {
        //You'll have to define the getDetailsOfFriend function
        return getDetailsOfFriend(friendId);
    });
}

并简单地称之为

getFriendsIds(123)
    .then(getFriendsDetails) //the resolved value from previous function will be passed as argument
    .then(function(friendDetails) {
        //friendDetails is an array of the details of each friend of the user with id 123
    })
    .catch(function(error){
       //Handle errors
    });

如果你想写更少的代码,你可以让bluebird promisify 像这样的猫鼬函数

Promise.promisify(User.findOne)(123)
    .then(function(user){
        return user.friendsIds;
    })
    .then(getFriendsDetails)
    .then(function(friendDetails) {
        //Return or do something with the details
    })
    .catch(function(error){
        //Handle error
    });