将响应传递给 $q promise 的第二个“then”
Pass response to the 2nd `then` of a $q promise
看看这个简单的例子:
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')
}
});
}
笨蛋:http://plnkr.co/edit/LHgTeL9sDs7jyoS7MJTq?p=preview
在这个例子中 res
在 testGetColors
函数中是 undefined
.
如何将 res
传递给 $q
promise 中的第二个 then
函数?
你需要returnres
function getColors() {
return colorPromise().then(function(res) {
console.log('getColors', res)
return res; // here
};
}
通过 return 在你的第一个 then
.:
function getColors() {
return colorPromise().then(function(res) {
console.log('getColors', res)
// do something with res
return res; //<---
};
}
.then
return本身就是一个承诺。如果您传递给它的 function
return 是一个非承诺值,则该承诺将立即用该 return 值解决(这就是您的情况,因为您的函数 returned undefined
(无))。请注意,您还可以 return 在 then
-function 中使用一个 promise,使 then
-promise 成为那个 promise。
您必须在 getColors
函数中执行 return res
,请参阅 this plunkr
看看这个简单的例子:
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')
}
});
}
笨蛋:http://plnkr.co/edit/LHgTeL9sDs7jyoS7MJTq?p=preview
在这个例子中 res
在 testGetColors
函数中是 undefined
.
如何将 res
传递给 $q
promise 中的第二个 then
函数?
你需要returnres
function getColors() {
return colorPromise().then(function(res) {
console.log('getColors', res)
return res; // here
};
}
通过 return 在你的第一个 then
.:
function getColors() {
return colorPromise().then(function(res) {
console.log('getColors', res)
// do something with res
return res; //<---
};
}
.then
return本身就是一个承诺。如果您传递给它的 function
return 是一个非承诺值,则该承诺将立即用该 return 值解决(这就是您的情况,因为您的函数 returned undefined
(无))。请注意,您还可以 return 在 then
-function 中使用一个 promise,使 then
-promise 成为那个 promise。
您必须在 getColors
函数中执行 return res
,请参阅 this plunkr