使用 Promise API,如何并行发送两个异步请求,并将组合结果解析为响应。
var get = function(id){
var res1, res2;
var deferred = $q.defer();
Db.get(id, "abc")
.then(function (d) {
//deferred.resolve(d));
res1 = d;
}, function (e) {
//error
});
Db.get(id, "def")
.then(function (d) {
//deferred.resolve(d));
res2 = d;
}, function (e) {
//error
});
//?????? how to return {res1:res1 , res2: res2}
return deferred.promise;
};
现在,当我像这样调用 get() 时
get(123).then(function(d)){
// d= {res1: res1, res2: res2}
},
...
我需要得到所示的合并结果。如何使用 Angular Promise API 做到这一点?
最佳答案
正如@Matt所说,您需要使用$q.all
,但用法不太正确。 AngularJS 不支持 .done
和 .fail
并且它们的工作方式并不像那样,因为不存在多个值的 promise ,相反你只需对数组有一个 promise 。
如果您使用完整的Q来写这篇文章我们会写:
var get = function (id) {
return Q.all([Db.get(id, "abc"), Db.get(id, "def")])
.spread(function (res1, res2) {
return {res1: res1, res2: res2};
});//the error case is handled automatically
};
在这种情况下,.spread
的作用类似于 .then
,只不过它将 Promise 的数组结果扩展到其 onFulfilled< 的参数上
函数。要更改此设置以使用 AngularJS 中的 Promise 方法,我们只需不用 .spread
即可。这导致了以下解决方案:
var get = function (id) {
return $q.all([Db.get(id, "abc"), Db.get(id, "def")])
.then(function (res) {
return {res1: res[0], res2: res[1]};
});//the error case is handled automatically
};
这样做的好处在于,我们无需处理错误传播的所有细节并存储部分结果,因为 .then
充当过滤器。如果省略错误处理程序,它会自动传播任何错误。这意味着如果任何一个输入 Promise 被拒绝,结果也将被拒绝。如果两个 promise 都成功实现,则 res 是这些分辨率值的数组。
关于javascript - Promise API - 合并 2 个异步调用的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16307652/