我需要對一個 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。
uj5u.com熱心網友回復:
你可以使用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
})
}
作業堆疊閃電戰
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/490617.html
