问题
Have a scenario where we have a loop and inside the loop we need to call a http
service to get information about each item in the loop.
Then based on the result of the service call we need to evaluate and do other work then continue on with each element in the loop.
I understand this will not work as coded due to the sync nature of the service call and that the service call itself is a promise.
Just looking at the best angular way to accomplish this. In the past I've used $q.all
but I'd have to make multiple loops it seems to accomplish using $q.all
.
_($scope.searchResult)
.each(function (results) {
var specialInfo = myService.getInfo(results); // http service call
if(specialInfo.length > 0){
// Do something
}
else
{
// Do something else
}
});
Please note to anyone responding I need the service to return before moving on as I will be showing a modal if conditions are met. The code above is pseudocode, I know the .Then is missing on the getInfo but you get the point. Each of the loops could potentially require user input to move on before reviewing the next item in the loop.
回答1:
Restructure your code so there is no loop, but recursive async calls:
var currentIndex = 0;
function processNext() {
if (currentIndex >= $scope.searchResult.length) {
return;
}
var next = $scope.searchResult[currentIndex++];
myService.getInfo(next).then(function (response) {
var specialInfo = response.data;
if (specialInfo.length > 0) {
// something
} else {
// something else
}
processNext();
});
}
processNext();
Alternatively, you could fetch all promises first and then process them one at a time. Keep in mind that this method wouldn't be advised if doing async processing on the responses (like waiting for input from a modal or executing subsequent requests):
var promises = $scope.searchResult.map(function (result) {
return myService.getInfo(result);
});
$q.all(promises).then(function (responses) {
responses.each(function (response) {
// do stuff
});
});
回答2:
To access the result of a promise, you use then()
:
_($scope.searchResult)
.each(function (results) {
myService.getInfo(results).then(function(response) {
var specialInfo = response.data;
if(specialInfo.length > 0) {
// Do something
}
else {
// Do something else
}
});
});
来源:https://stackoverflow.com/questions/33354836/need-to-call-angular-http-service-from-inside-loop-and-wait-for-the-value-of-the