承诺正在等待中

Dan*_*man 7 node.js promise bluebird

我的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);
        });
     });
};
Run Code Online (Sandbox Code Playgroud)

当我在调用类时,id正在等待:

var currentRole = new Role(myRole, comId);
console.log(currentRole);
Run Code Online (Sandbox Code Playgroud)

如何在解决时从类中获取值?

Mat*_*son 4

currentRole.id是一个承诺,因此您可以调用then()它来等待它得到解决:

var currentRole = new Role(myRole, comId);
currentRole.id.then(function (result) {

    // do something with result
});
Run Code Online (Sandbox Code Playgroud)

不过,这感觉像是一个奇怪的 API,您希望您的对象在其构造函数返回时“准备好使用”。getId在原型上有一个承诺返回函数可能会更好Role,所以你可以这样做:

var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {

    // do something with result
});
Run Code Online (Sandbox Code Playgroud)

您还应该考虑处理该错误以拒绝承诺:

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);
        });
     });
};
Run Code Online (Sandbox Code Playgroud)

并将拒绝处理程序添加到您的调用中getId

var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {

    // do something with result
}, function (err) {

    // do something with err
});
Run Code Online (Sandbox Code Playgroud)

或等价:

var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {

    // do something with result
}).catch(function (err) {

    // do something with err
});
Run Code Online (Sandbox Code Playgroud)