我正在嘗試$scope.results = []通過多個順序 API 呼叫來依次填充我的內容。順序很重要,因為我要傳入一個開始和一個限制數(類似于分頁)。由于 API 網關在 30 秒后超時,我無法在 1 次呼叫中執行此操作并且需要中斷多次呼叫是有原因的。
我的問題是在 for 回圈中它不能按順序作業。在陣列內部,所有網路請求似乎都獲得了相同的start值,并且不是按順序發送的。我也不能用async/await。有沒有辦法按順序運行 API 呼叫并將結果添加到results陣列中。我的最終目標是像在單個 API 呼叫中那樣填充陣列,但需要多次呼叫
$scope.detailedReportOfAll = function () {
$scope.start = 0;
$scope.limit = 15;
$scope.results = [];
var requestCount = 1;
APIService.getDetailedReportData($scope.start,$scope.limit).then(
function ({result,nbPages}) {
if (result.length){
$scope.results = $scope.results.concat(result);
requestCount ;
$scope.start = $scope.limit;
}
if (requestCount < nbPages){ //I'm running the loop for (nbPages - 1) times
for (i=2; i<nbPages; i ){
APIService.getDetailedReportData($scope.start,$scope.limit).then(
function ({result,nbPages}) {
if (result.length){
$scope.results = $scope.results.concat(result);
requestCount ;
console.log($scope.results, requestCount)
$scope.start = $scope.limit;
}
})
}
}
}
);
};
這是我的 http 呼叫函式。它回傳一個承諾
var getDetailedReportData= function (start, limit) {
$rootScope.isLoading = true;
var deferred = $q.defer();
$http
.get(rootURL('/getAllReports/' start '/' limit))
.success(function (response) {
deferred.resolve(response);
})
.catch(function (err) {
deferred.reject(err);
})
.finally(function () {
$rootScope.isLoading = false;
});
return deferred.promise;
};
非常感謝幫助
uj5u.com熱心網友回復:
如果你想連續運行這些,那么當你知道異步函式n-1完成時,你需要觸發異步函式n;即在回呼中。如果您拒絕了and ,遞回呼叫函式可能是最簡單的方法。thenasyncawait
function somethingAsync(value) {
return new Promise(res => setTimeout(res, 500, value * value));
}
function processInputInSeries(input) {
function processNext(index, input, results) {
if (index >= input.length) return results;
return somethingAsync(input[index]).then(function (result) {
return processNext(index 1, input, [...results, result]);
});
}
return processNext(0, input, []);
}
const resultPromise = processInputInSeries([1,2,3]);
resultPromise.then(function(results) { console.log(results) });
為了比較,async/await更清晰:
function somethingAsync(value) {
return new Promise(res => setTimeout(res, 500, value * value));
}
async function processInputInSeries(input) {
let results = [];
for (let i = 0; i < input.length; i ) {
const result = await somethingAsync(input[i]);
results = [...results, result];
}
return results;
}
const resultPromise = processInputInSeries([1,2,3]);
resultPromise.then(function(results) { console.log(results) });
即使您最終使用 Babel 轉換您的 JS 以與過時的系統兼容,我也建議您這樣撰寫它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434275.html
