简体   繁体   中英

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.

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);        
    });               
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM