【问题标题】:bluebired promisify function not converted to promise蓝鸟承诺功能未转换为承诺
【发布时间】:2017-04-25 17:10:08
【问题描述】:

他们还有什么其他的方式来实现承诺吗?

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

我在 .then() 中像 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;
            });

它给出了一个错误:-

无法读取未定义的属性“then”

【问题讨论】:

  • it gives an error - 是什么?你发布的代码? (不太可能,你不使用.then)——你确定你知道你在用 Promise 做什么吗?
  • promisify 不返回一个承诺 - 它返回一个 function ,当被调用时返回一个承诺。你怎么称呼它?
  • mongoose-find-one-or-create 模块有缺陷(竞争条件),你应该考虑使用内置的findOneAndUpdate 结合upsert : true。这也意味着你不必承诺任何东西,因为 Mongoose 支持承诺 out of the box

标签: javascript node.js mongoose bluebird


【解决方案1】:

首先,根据bluebird documentation

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

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(...)

【讨论】:

  • 它被转换成承诺,但它不能正常工作..我尝试使用回调函数它在那里工作 aud
猜你喜欢
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 2014-02-13
  • 2014-11-06
  • 2015-09-06
相关资源
最近更新 更多