Question: **JAVASCRIPT**

```
for (var i=0; i<$scope.length; i++)
{
    var data = {
        page_no:i
    };
    newlocalitemService.list(data, function(res) { 
        $scope.data.push(res);
   });
}

```

**newlocalitemService**

```
list: function(data,success,error){
    $http({
        url: CONFIG.apiUrl + '/items',
        method: "GET",
        params: data
        }).success(success).error(error);
}

```

I'm calling API in for loop. How to call each API after getting response. Here $scope.data initialized as an array and API is asynchronous method.

Answer: 
Some kind of recursive function that calls itself until the end of the collection:

```
function doStuff(arr, idx) {
    if (idx <= (arr.length - 1)) {
        newlocalitemService.filter(arr[idx], function(res) { 
            $scope.data.push(res);
            doStuff(arr, ++idx);
        });
    }
}

doStuff($scope.data, 0);

```
You will need to insert the for loop inside a callback function once you retrive the AJAX data, like so (in JQuery):

```js
var dataFromServer;  //declare the variable first

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData(dataFromServer)
    })
}

function handleData(data) {
    alert(data);
    //insert your for loop here

}
```