[英]Cannot get my promise to return in nodejs / mongoose / bluebird
我正在使用藍鳥。
我還使用了藍鳥的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'));
在我的整個項目中,它一直成功運行,但是由於某種原因,我無法使它返回此“保存”方法的collections值。
這是我的模型:
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);
})
};
我真的可以用另一雙眼睛指出我出了問題的地方。
您不應該使用…Async
已經返回諾言的函數的…Async
承諾版本。 這只會導致Bluebird傳遞一個從未調用的附加回調。
Collection.createCollection({user: req.user._id, whiskey: req.body.whiskey}).then(function(data){
res.send(data);
}, function(err) {
…
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.