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 isundefined
– 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
1 Answer
Reset to default 7Do 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
版权声明:本文标题:javascript - Return another promise from a promise - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745295067a2652025.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论