[英]How to make async calls in angularJS using $promise?
我需要对一个 api 进行多次调用,并将结果连接起来。 我正在使用 angularJS
$scope.myFunction = function() {
let res;
for (//some condition) {
let data = MyService.query();
data.$promise.then(function(r){
// here I receive the response from the api and I "concatenate" the result in a variable
res += r.someValue;
}
}
// here I need to do something with **res** when all the api calls are done
}
问题是在所有 api 调用返回结果之前执行了for循环之外的代码。
如何在for循环之后编写代码以等待循环内的所有代码执行完毕,并且res变量已完全填充? 使用 async/await 不起作用,因为我收到此错误
"angular.js:12808 ReferenceError: regeneratorRuntime is not defined"
目前我无法将包添加到 package.json。
你可以使用Promise.all 之类的东西
$scope.myFunction = function() {
let res=[];
for (//some condition) {
let data = MyService.query();
let respPromise= data.$promise.then(function(r){
// return the response
return r.someValue;
})
res.push(respPromise);
}
Promise.all(res).then(data=>{
console.log(data);//data should contains all the responses here
})
}
工作堆栈闪电战
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.