简体   繁体   中英

Return another promise from a promise

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.

Do not use the deferred antipattern 1 ! 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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM