2016-04-24 163 views
6

我有一个类中我用下面的代码的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

当出现'err'时,应该'拒绝'。 – Bergi

+0

看看[是不是很好的做法,有一个构造函数返回一个Promise?](http://stackoverflow.com/q/24398699/1048572) - 你可能不想做'currentRole.id.then (...)' – Bergi

回答

3

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

谢谢你马特! 我用你最后的建议,现在的代码工作,看起来更干净。 –