[英]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.