admin管理员组

文章数量:1418697

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.

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.

Share Improve this question edited Apr 11, 2015 at 11:44 Bergi 667k161 gold badges1k silver badges1.5k bronze badges asked Apr 11, 2015 at 11:28 mushroommushroom 1,9453 gold badges16 silver badges33 bronze badges 5
  • Yes, this looks fine. Even ES6 Promises have similar structure only. – thefourtheye Commented Apr 11, 2015 at 11:32
  • Why don't you chain user instead? user.then(function() {}, function() {}). You also may return a scalar value from the promise. – zerkms Commented Apr 11, 2015 at 11:36
  • You are not returning resolve, so accessToken is undefined – Krzysztof Safjanowski Commented Apr 11, 2015 at 11:37
  • @KrzysztofSafjanowski Updated! ^ – mushroom Commented Apr 11, 2015 at 11:42
  • I highly remend reading the Promises/A+ specification. It isn't long, pretty understandable and applies to almost any promise library: promisesaplus. – Zenorbi Commented Apr 11, 2015 at 11:47
Add a ment  | 

1 Answer 1

Reset to default 7

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 :-)

本文标签: javascriptReturn another promise from a promiseStack Overflow