mongoose升级后async不会在callback中返回数据

在我的项目中,我使用asynchronous查询到数据库,我有这段代码:

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

返回friends的ID的方法如下所示:

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

它工作完美。 该函数返回了朋友的ID,我用它们在“两个”asynchronous调用块。

mongoose4.3.7升级到4.7.8 ,停止工作。 我开始获取Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead警告和id不再在callback中返回。

所以我给项目添加了bluebird软件包,并将其插入mongoose 。 现在警告消失了,但是ID仍然没有在callback中返回。

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

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

使用承诺的想法是不使用callback,而且您仍然在代码中使用callback。

假设你需要蓝鸟

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的数组。 利用承诺的链接可能性,您可以编写一个函数来获取每个朋友的详细信息,并以friendDetails数组的formsfriendDetails

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

如果你想写更less的代码,你可以让蓝鸟promisify这样的mongoose函数

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