user3679607
user3679607

Reputation: 163

Javascript Web API call in for loop

I am developing an app with angularjs and ionic. There I have an array with ids. And from all these ids I need to have a name. Now I tried it with the code below:

var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
var arrayWithNames = [];

for (var j = 0; j < arrayWithIds.length; j++) {
    ResourceService.get(arrayWithIds[j]).then(function(resource) {
        arrayWithNames.push(resource.Name);                  
    },function(error) {
        alert(error.message);        
    });               
}

$scope.resources = arrayWithNames;

It is all ok when I debug. I always get the name back. But in $scope.resources there is nothing, it is empty, also the array arrayWithNames.

Do I miss something? What is the problem?

Thanks.

Upvotes: 1

Views: 1353

Answers (1)

franciscod
franciscod

Reputation: 1000

The ResourceService.get() call is asynchronous (and also a Promise), and this line

$scope.resources = arrayWithNames;

is getting called before the ResourceService.get() callback.

You can drop arrayWithNames and directly push to $scope.resources:

var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
$scope.resources = [];

for (var j = 0; j < arrayWithIds.length; j++) {
    ResourceService.get(arrayWithIds[j]).then(function(resource) {
        $scope.resources.push(resource.Name);                  
    },function(error) {
        alert(error.message);        
    });               
}

Upvotes: 2

Related Questions