【发布时间】: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