Promises TypeError:在非对象上调用的函数resolve

时间:2017-07-08 17:55:48

标签: node.js promise bluebird

我对承诺不熟悉,并认为我可能会混淆从承诺中返回的内容并传递给.then.catch块。我在下面的注释行中得到一个TypeError,但是当我从

更改它时
.then(Promise.resolve)

要     .then((obj)=> {Promise.resolve(obj);})

错误消失。这有什么区别?我是否误解了应该如何锁定承诺呢?

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.set('debug', true);
var FoodItem = require('../models/FoodItem.js');
var UserFoodItem = require('../models/UserFoodItem.js');
var User = require('../models/User.js');

var StockController = {};
StockController.createUserFoodItem = function(userId, {name, qty}) {
    var userItem = new UserFoodItem({
        user: new mongoose.Types.ObjectId(userId),
        dateAdded: new Date(),
        quantity: qty
    });

    return new Promise((resolve, reject) => {
        FoodItem.findOne({ 'name': name })
            .then((foodItem) => {
                if (foodItem) {
                    userItem.foodItem = foodItem; 
                    userItem.save().then((userFoodItem) => {
                        resolve(userFoodItem);
                    });
                } else {
                    reject(new Error('No food item yet!'))
                }
            });
    });
}

StockController.addFoodItemToFridge = function (userId, {name, qty}) {
    return StockController.createUserFoodItem(userId, {name, qty})
        .then((userFoodItem) => {
            User.findByIdAndUpdate(userId, 
                { $push: { "fridge": userFoodItem }},
                { new: true }
            ).then(Promise.resolve) // ERROR OCCURS HERE
            .catch(console.log);
       })
        .catch(console.log("hello"));
}

错误:

TypeError: function resolve() { [native code] } called on non-object
    at resolve (native)
    at tryCatcher (/Users/jessy/herb/node_modules/bluebird/js/main/util.js:26:23)
    at Promise._settlePromiseFromHandler (/Users/jessy/herb/node_modules/bluebird/js/main/promise.js:507:31)
    at Promise._settlePromiseAt (/Users/jessy/herb/node_modules/bluebird/js/main/promise.js:581:18)
    at Promise._settlePromises (/Users/jessy/herb/node_modules/bluebird/js/main/promise.js:697:14)
    at Async._drainQueue (/Users/jessy/herb/node_modules/bluebird/js/main/async.js:123:16)
    at Async._drainQueues (/Users/jessy/herb/node_modules/bluebird/js/main/async.js:133:10)
    at Immediate.Async.drainQueues (/Users/jessy/herb/node_modules/bluebird/js/main/async.js:15:14)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)

0 个答案:

没有答案