Promise Pending

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 call the class, id expects:

 var currentRole = new Role(myRole, comId); console.log(currentRole); 

How can I get values ​​from a class when resolving them?

+6
source share
1 answer

currentRole.id is a promise, so you can call then() on it to wait for its resolution:

 var currentRole = new Role(myRole, comId); currentRole.id.then(function (result) { // do something with result }); 

This seems like a weird API, but you expect your object to be "ready to use" when its constructor returns. It is better to have the getId promise return function on a Role prototype, so that you do something like this instead:

 var currentRole = new Role(myRole, comId); currentRole.getId().then(function (result) { // do something with result }); 

You should also consider handling this error in order to reject a 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 getId call:

 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 }); 
+3
source

All Articles