【问题标题】:Cannot get my promise to return in nodejs / mongoose / bluebird无法得到我在 nodejs / mongoose / bluebird 中返回的承诺
【发布时间】:2016-11-24 09:34:04
【问题描述】:

我正在使用蓝鸟。

我还为模型使用了 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
              };
            });
          }
        })
      };

这里是控制器,其中调用了 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);
  })
};

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

【问题讨论】:

    标签: javascript node.js mongoose promise bluebird


    【解决方案1】:

    你不应该使用已经返回承诺的函数的…Async承诺版本。这只会导致 Bluebird 传入一个从未调用过的额外回调。

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

    【讨论】:

    • 有道理。再次感谢@Bergi。我欠你帮助我解决这个问题。
    猜你喜欢
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 2018-05-11
    • 2017-04-09
    • 1970-01-01
    • 2014-09-07
    • 2020-09-21
    相关资源
    最近更新 更多