bluebired promisify函数未转换为promise

时间:2017-04-25 08:05:14

标签: javascript node.js mongoose bluebird

是他们转换为诺言的任何其他方式吗?

var Promise = require("bluebird");
let findOneOrCreate = require('mongoose-find-one-or-create');
findOneOrCreate = Promise.promisify(findOneOrCreate); // not converted to promise

我在.then()中使用的那样: -

        db.employee.findOneOrCreate({
                organization: model.organization.id,
                EmpDb_Emp_id: model.EmpDb_Emp_id
            }, model)
            .then((employee, created) => {
                if (!created) {
                    throw 'employee already exist';
                }
                return employee;
            }).catch(err => {
                throw err;
            });

它出错: -

无法读取“未定义”属性

1 个答案:

答案 0 :(得分:2)

首先,根据bluebird documentation

  

节点函数应符合接受a的node.js约定   回调作为最后一个参数

mongoose-find-one-or-create仅接受schema作为参数,并使用findOneOrCreate函数扩展此架构。所以似乎require('mongoose-find-one-or-create')不能被宣传。您可以尝试宣传扩展架构的findOneOrCreate

var findOneOrCreate = require('mongoose-find-one-or-create');
var PersonSchema = mongoose.Schema({...});
PersonSchema.plugin(findOneOrCreate);
var Person = mongoose.model('Person', PersonSchema);
var findOneOrCreatePromise = Promise.promisify(Person.findOneOrCreate);

另请注意Promise.promisify()会返回一个函数,因此您需要在调用then之前调用它:

findOneOrCreatePromise().then(...)

不仅仅是

findOneOrCreatePromise.then(...)