在执行一行代码之前,是否有方法等待多个API调用响应?
通常,我使用:
APIService.call(parameter).then(function(response) {
// Do things
callBack();
});这很好,callBack()是在APIService.call()的回答之后执行的。
但是假设我有3个不同的API调用,如下所示:
$scope.var1 = APIService.call1(parameter)
$scope.var2 = APIService.call2(parameter)
$scope.var3 = APIService.call3(parameter)我希望我的回呼在3个呼叫应答后被调用,这意味着在最长的应答之后。我怎么能这么做?我不想做嵌套的then,因为我希望我的3个调用一直被异步调用。
这可行吗?
发布于 2017-10-26 13:28:19
由于您使用的是AngularJS,所以可以使用$q.all。做以下事情:
var promises = [];
promises.push(APIService.call1(parameter));
promises.push(APIService.call2(parameter));
promises.push(APIService.call3(parameter));
$q.all(promises).then(function (values) {
// you can access the response from each promise
$scope.var1 = values[0];
$scope.var2 = values[1];
$scope.var3 = values[2];
doSomething();
})发布于 2017-10-26 13:29:12
您可以使用$q.all()方法,只需向它传递一组您想要解决的承诺,它所做的就是接受承诺数组,并返回一个承诺,一旦所有原始承诺都被解决,这个承诺就会解决。
$q.all([
APIService.call1(parameter),
APIService.call2(parameter),
APIService.call3(parameter),
]).then(function(data) {
//TODO: something...
});https://stackoverflow.com/questions/46955613
复制相似问题