简体   繁体   中英

Cannot get my promise to return in nodejs / mongoose / bluebird

I'm using bluebird.

I've also used bluebird's Promisify for the models.

var Promise = require('bluebird');
var mongoose = Promise.promisifyAll(require('mongoose')); 
var Collection = Promise.promisifyAll(require('../models/collection'));
var Vote = Promise.promisifyAll(require('../models/vote'));

throughout my project, it has been working successfully, but for some reason, I cannot get it to return the collections value on this 'save' method.

Here is my model:

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

Here is the controller, where the collectionCreate method is invoked and expecting a response 'data' from the promise. However, the saveAsync mongoose method does not seems to invoke or return :

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

I could really use a second set of eyes to point out where I went wrong.

You are not supposed to use the …Async promisified versions of functions that already return promises. That will only lead to Bluebird passing in an additional callback that is never called.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM