I have a class in my nodejs application with the following code:
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);
});
});
};
When I am calling the class, the id is pending:
var currentRole = new Role(myRole, comId);
console.log(currentRole);
How can I get the values from the class when they are resolved?
pending: The promise is in it's initial state, it has not completed it's operation nor has it failed. fulfilled: The operation has completed successfully. rejected: The operation has failed.
The promise will always log pending as long as its results are not resolved yet. You must call . then on the promise to capture the results regardless of the promise state (resolved or still pending): Promises are forward direction only; You can only resolve them once.
The await expression is usually used to unwrap promises by passing a Promise as the expression . This causes async function execution to pause until the promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.
currentRole.id
is a promise so you can call then()
on it to wait for it to be resolved:
var currentRole = new Role(myRole, comId);
currentRole.id.then(function (result) {
// do something with result
});
This feels like a strange API though, you expect your object to be "ready to use" when its constructor returns. Might be better to have getId
be a promise returning function on the prototype of Role
so you instead do something like:
var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {
// do something with result
});
You should also consider handling that error to reject the promise:
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);
});
});
};
and add a rejection handler to your call to getId
:
var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {
// do something with result
}, function (err) {
// do something with err
});
or equivalently:
var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {
// do something with result
}).catch(function (err) {
// do something with err
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With