简体   繁体   中英

Promise is 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 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM