This question already has answers here:
Aren't promises just callbacks?

(10个回答)


5年前关闭。




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

然后我想到了这样的东西:
$http.get('/xxx').then(function(response){
    $http.get('/yyy').then(function(response){
        //do something
    })
});

但是我毕竟想返回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;

但是我不明白为什么会起作用???

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

但是如果我打电话
promise.then(function(data){
    console.log(data);
});

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

最佳答案

当您从Promise .then(…)回调返回一个Promise时,Promise库将自动等待内部Promise解析,然后将使用该值解析返回的Promise。

换句话说,如果您 promise 一个 promise ,您将获得其内在值(value)。

这是应许之美的一部分。您可以通过利用此功能并链接您的 promise 来减少嵌套:

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

有关更多详细信息,请参见my blog

09-25 17:13
查看更多