gpt4 book ai didi

javascript - bluebird promisify 函数未转换为 Promise

转载 作者:行者123 更新时间:2023-12-01 03:45:33 25 4
gpt4 key购买 nike

他们还有其他方式进行 promise 转换吗?

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

它给出了一个错误:-

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

最佳答案

首先根据bluebird documentation ,

the node function should conform to node.js convention of accepting a callback as last argument

mongoose-find-one-or-create仅接受 schema 作为参数,并使用 findOneOrCreate 函数扩展此架构。所以看来 require('mongoose-find-one-or-create') 不能被 promise 。您可以尝试 promise 扩展模式的 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(...)

关于javascript - bluebird promisify 函数未转换为 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43604945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com