小编Dem*_*ane的帖子

AngularJs:返回嵌套$ http的承诺 - 已找到解决方案,但为什么会有效?

我想在第一次成功之后构建一个嵌套的$ http.get,然后请求第二个.

然后我出来了这样的事情:

$http.get('/xxx').then(function(response){
    $http.get('/yyy').then(function(response){
        //do something
    })
});
Run Code Online (Sandbox Code Playgroud)

但我毕竟想要返回一个Promise,以便我可以正确地组织我的代码.显然上面的代码不符合我的需要.

然后我做了很多研究$q.all(),但实际上用$ q.all,第二个请求不等待第一个请求,即使第一个请求没有成功响应,它也会发送第二个请求.

在那之后,我找到了一个解决方案,在我的情况下就像一个魅力:

var promise = $http.get('/xxx').then(function(response1){
    return $http.get('/yyy').then(function(response2) {
        return response2.data;
    });;
});     
return promise;
Run Code Online (Sandbox Code Playgroud)

但我不明白为什么会有效?

在第一个promise($ http.get)的success函数中,它返回第二个promise作为then()函数的参数.

但如果我打电话

promise.then(function(data){
    console.log(data);
});
Run Code Online (Sandbox Code Playgroud)

我发现这里打印的数据是response2.data,怎么可能呢?不应该是第二个$ http 的Promise对象 ???

javascript promise angularjs

5
推荐指数
1
解决办法
6881
查看次数

标签 统计

angularjs ×1

javascript ×1

promise ×1