2016-07-21 52 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