javascript - 无法得到我在 nodejs/mongoose/bluebird 中返回的 promise

标签 javascript node.js mongoose promise bluebird

我正在使用 Bluebird 。

我还使用了 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'));

在我的整个项目中,它一直运行成功,但由于某种原因,我无法让它在这个“保存”方法上返回集合值。

这是我的模型:

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

这里是 Controller ,其中调用了 collectionCreate 方法并期望来自 Promise 的响应“数据”。但是,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 promise 版本。这只会导致 Bluebird 传递一个从未被调用的额外回调。

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

关于javascript - 无法得到我在 nodejs/mongoose/bluebird 中返回的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493262/

相关文章:

javascript - 使用来自 mysql (laravel) 的数据显示带有标记的谷歌地图

javascript - 通过javascript中的选择选项更改字体大小

node.js - npm cache clean 中 -f(强制?)参数的行为是什么?

node.js - 在 mongodb 中保存或更新文档时如何防止更新 "updatedAt"字段?

javascript优秀导出blob问题

javascript - vue js 将数据传递给组件

performance - 在express中使用nodejs可以采取哪些措施来提高jade模板渲染性能

javascript - Express 路由中的可选 GET 参数

javascript - MongooseJS findOne() 的意外结果

node.js - 警告 : Accessing non-existent property 'MongoError' of module exports inside circular dependency