約束

2016-04-24 14 views
6

を保留している私は、次のコードで私のnodejsアプリケーションでクラスを持っています解決されたクラスからの値?約束

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

    // do something with result 
}); 

これはしかし奇妙なAPIのように感じている、あなたのオブジェクトは時に「使用する準備」であることを期待:

+0

「エラー」がある場合は、「拒否」する必要があります。 – Bergi

+0

[コンストラクター関数がプロミスを返すのは悪い習慣ですか?](http://stackoverflow.com/q/24398699/1048572) - おそらく 'currentRole.id.then (...) ' – Bergi

答えて

3

currentRole.idは、あなたがそれを解決するのを待つことにthen()を呼び出すことができるように約束ですそのコンストラクタは返します。ような何かgetIdRoleのプロトタイプに機能を返す約束も持っている方が良いかもしれませんので、あなたの代わりに:

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

マットありがとう! 私はあなたの最後の提案を使用し、コードは今動作し、よりきれいに見えます。 –