无法在nodejs/mongoose/bluebird中获得返回的承诺
Cannot get my promise to return in nodejs / mongoose / bluebird
我正在使用bluebird。
我还使用了蓝鸟的Promiseify作为模型。
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方法,并期望来自promise的响应"data"。但是,saveAsync mongoose方法似乎不会调用或返回:
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);
})
};
我真的可以用第二双眼睛来指出我做错了什么。
您不应该使用已经返回promise的函数的…Async
promised版本。这只会导致Bluebird传入一个从未调用过的额外回调。
Collection.createCollection({user: req.user._id, whiskey: req.body.whiskey}).then(function(data){
res.send(data);
}, function(err) {
…
})
相关文章:
- 谷歌日历 api 调用可以在角度工厂内返回承诺吗?
- JavaScript - 返回承诺和/或调用回调
- 在同一函数中解析承诺后返回承诺
- 承诺返回承诺
- 承诺返回承诺
- 如何从多个承诺中返回承诺
- 如何使用在 AngularJS 中返回承诺的$resource测试工厂
- 这是一种常见的模式吗?(返回数据而不是返回承诺)
- 使用 Jasmine 2.4.* 测试返回承诺的服务
- 承诺回调返回承诺
- 可以 Angular 模板调用函数返回承诺
- 链接返回承诺数组的函数
- 使用属性从指令返回承诺
- 节点.js SQLite 3 返回承诺
- 从延迟的回调中返回承诺
- 返回承诺与返回承诺内未定义之间的区别
- 返回承诺值
- 如何在返回承诺的服务中创建 reset() 方法
- 从顺序 jQuery ajax 调用返回承诺
- 在 Redux Thunk 发货后从商店返回承诺