我的nodejs应用程序中有一个类,代码如下:
var mongoose = require('mongoose');
var Roles = mongoose.model('roles');
var Promise = require("bluebird");
module.exports = Role;
var err = null;
var id;
function Role(name, companyId) {
this.err = err;
this.name = name;
this.companyId = companyId;
this.id = getId(name, companyId);
}
var getId = function (name, companyId) {
return new Promise(function(resolve, reject) {
Roles.findOne({companyId:companyId, name:name}, function(err,result) {
resolve(result._id);
});
});
};
当我呼叫班级时,该ID正在等待:
var currentRole = new Role(myRole, comId);
console.log(currentRole);
如何在解析时从类中获取值?
答案 0 :(得分:4)
currentRole.id
是一个承诺,因此您可以在其上调用then()
等待其解决:
var currentRole = new Role(myRole, comId);
currentRole.id.then(function (result) {
// do something with result
});
这感觉就像一个奇怪的API,你希望你的对象在构造函数返回时“随时可以使用”。可能最好让getId
成为Role
原型上的承诺返回函数,这样你可以做类似的事情:
var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {
// do something with result
});
您还应考虑处理该错误以拒绝承诺:
var getId = function (name, companyId) {
return new Promise(function(resolve, reject) {
Roles.findOne({companyId:companyId, name:name}, function(err,result) {
if (err) {
return reject(err);
}
resolve(result._id);
});
});
};
并在您对getId
的调用中添加拒绝处理程序:
var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {
// do something with result
}, function (err) {
// do something with err
});
或等效地:
var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {
// do something with result
}).catch(function (err) {
// do something with err
});