2016-07-21 24 views
0

我正在使用蓝鸟。不能得到我的承诺返回nodejs/mongoose /蓝鸟

我也使用蓝鸟的Promisify模型。

var Promise = require('bluebird'); 
var mongoose = Promise.promisifyAll(require('mongoose')); 
var Collection = Promise.promisifyAll(require('../models/collection')); 
var Vote = Promise.promisifyAll(require('../models/vote')); 

在我的项目,它已经成功地工作,但由于某些原因,我不能让它在这个“拯救”方法返回集合值。

这是我的模型:

var CollectionSchema = new mongoose.Schema({ 
    user : {type: mongoose.Schema.ObjectId, ref: 'User', required: true}, 
    whiskey : {type: mongoose.Schema.ObjectId, ref: 'Whiskey', required: true}, 
    favorite: {type: Boolean, default: false}, 
    timestamp: { type : Date, default: Date.now } 
}); 

    CollectionSchema.statics.createCollection = function(o) { 
     console.log('hit model') 
     return Collection 
     .findAsync(o) 
     .then(function(existing) { 
      console.log('existing collection ', existing) 
      if (existing.length) { 
      return{ 
       message: 'already collected' 
      } 
      } else { 
      console.log('no existing collections found') 
      return Collection 
      .saveAsync(o) 
      .then(function(collection) { 
       console.log('new collection/does not console.log ', collection) 
       return { 
       collection: collection 
       }; 
      }); 
      } 
     }) 
     }; 

这里是控制器,其中collectionCreate方法被调用,并期望从承诺的响应“数据”。然而,saveAsync猫鼬方法似乎并不调用或返回:

exports.create = function(req, res){ 
    console.log('init') 
    console.log('init body ', req.body) 
    Collection.createCollectionAsync({user: req.user._id, whiskey: req.body.whiskey}).then(function(data){ 
    console.log('collection promise ', data) 
    res.send(data); 
    }) 
}; 

我真的可以使用第二组的眼睛指出我哪里错了。

回答

1

你不应该使用…Async promisified版本的已经返回promise的函数。这只会导致蓝鸟传递一个从未被调用的额外回调。

Collection.createCollection({user: req.user._id, whiskey: req.body.whiskey}).then(function(data){ 
    res.send(data); 
}, function(err) { 
    … 
}) 
+0

有意义。再次感谢@Bergi。我欠你帮忙把我的头包裹起来。 – NoobSter