看看这个简单的例子:
function colorPromise() {
return $q.when({data:['blue', 'green']})
}
function getColors() {
return colorPromise().then(function(res) {
console.log('getColors', res)
// do something with res
};
}
function testGetColors() {
getColors().then(function(res) {
if (angular.equals(res, {data:['blue', 'green']})) {
console.log('passes')
}
});
}
Plunker:http://plnkr.co/edit/LHgTeL9sDs7jyoS7MJTq?p=preview
在此示例中,res
函数中的testGetColors
为undefined
。
如何将res
传递给then
承诺中的第二个$q
函数?
答案 0 :(得分:5)
您需要返回res
function getColors() {
return colorPromise().then(function(res) {
console.log('getColors', res)
return res; // here
};
}
答案 1 :(得分:1)
将其返回到您的第一个then
。:
function getColors() {
return colorPromise().then(function(res) {
console.log('getColors', res)
// do something with res
return res; //<---
};
}
.then
会返回一个承诺。如果你传递给它的function
返回了一个非promise值,那么该promise将立即用该返回值解析(这是你的情况下发生的事情,因为你的函数返回undefined
(没有)) 。请注意,您还可以在then
- 函数中返回一个承诺,以使then
- 承诺成为承诺。
答案 2 :(得分:1)
您必须在return res
函数中执行getColors
,请参阅this plunkr