将响应传递给$q承诺的第二个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
本例中testGetColors
函数中的res
为undefined
。
如何将res
传递给$q
承诺中的第二个then
函数?
您需要返回res
function getColors() {
return colorPromise().then(function(res) {
console.log('getColors', res)
return res; // here
};
}
通过在您的第一个then
.:
function getColors() {
return colorPromise().then(function(res) {
console.log('getColors', res)
// do something with res
return res; //<---
};
}
.then
返回承诺本身。如果您传递给它的function
返回了一个非承诺值,则该承诺将立即用该返回值解决(这就是在您的情况下发生的情况,因为您的函数返回undefined
(什么都没有))。请注意,您也可以在then
-函数中返回一个承诺,以使then
-promise成为该承诺。
您必须在getColors
函数中执行return res
,参见此plunkr
相关文章:
- 下拉选择可自动更改第二个下拉选择
- 为什么不'在JQuery中找到第二个css选择器的工作
- 当单击第一个李时,它显示内容一,当单击第二个李时,它显示内容二
- CORS-重定向到第二个GET正在接收的页面
- 正则表达式与数字中的第二个点匹配
- 如何在react js中移动第二个组件
- 使用Javascript,如何显示<tr>在另一<tr>悬停时,隐藏第二个<tr>
- 关闭第二个事件源上的第一个事件源's onopen方法
- D3从嵌套的JSON中绘制第二个圆环图
- IE11中的第二个调用取消了第一个Fetch API调用
- 第一个字第一个字符第二个字第二个字符,一直到数组结束
- 角度指令:指向第二个元素
- 时间选择器:如何通过更改第一个值来更改第二个值
- 承诺,如果第一个失败,则返回第二个承诺结果
- React Native Fetch:第二个承诺挂起
- Angular 在第一个表单验证/承诺后提交第二个表单
- AngularJS:承诺链不延迟超过第二个函数
- 如何触发一个承诺,然后触发第二个承诺,$q
- 第二个承诺决心不解雇
- 将响应传递给$q承诺的第二个then