Reputation: 1945
I have a promise for an object and would like to get a promise for a property of that object. How should I do that?
var user = Q.nfcall(User.findOne, {
_id: userId
});
var accessToken = Q.Promise(function (resolve, reject) {
user.then(function (user) {
if (!user) return reject(new Error('User not found.'));
if (!user.github.accessToken) return reject(new Error('Access token not found.'));
return resolve(user.github.accessToken);
}, function(err) {
return reject(err);
});
});
This is what I tried so far, but I'm not sure if its the best (or most correct) way.
Upvotes: 3
Views: 3333
Reputation: 664538
Do not use the deferred antipattern1! There's no need to use Promise
constructor, .then
already returns you a promise for the result of its callback:
var accessToken = user.then(function(user) {
if (!user) throw new Error('User not found.');
if (!user.github.accessToken) throw new Error('Access token not found.');
return user.github.accessToken;
});
[1]: You've seen yourself how errorprone it is :-)
Upvotes: 7