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

Dem*_*ane 5 javascript promise angularjs

我想在第一次成功之后构建一个嵌套的$ 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对象 ???

SLa*_*aks 12

当您从promise .then(…)回调中返回promise时,promise库将自动等待内部promise进行解析,然后将使用该值解析返回的promise.

换句话说,如果你承诺一个承诺,你将获得其内在价值.

这是承诺之美的一部分; 你可以通过利用这个功能和链接你的承诺来减少嵌套:

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

有关详细信息,请参阅我的博客.