I have created an angular js custom service in a .js file.The service has various function that takes a key and returns me an array according to the input. In another js I am running a for loop over a list of keys and for each key I wish to generate the array.But the issue I am facing is that the for loop completes first and then only the pending call to the service function is made?
service with getData function:
rootApp.service('APIService', ['$http','$q', function ($http, $q) {
this.getData = function (key) {
var deferred = $q.defer();
if (key=== null || key=== undefined) {
deferred.reject({
error: 'Endpoint not properly configured'
});
} else {
$http({
method: 'GET',
url: "/api/getter/" + key
}).then(function (response) {
// console.log('Got the http request data response for endpoint: ' + urlEndPoint);
deferred.resolve(response.data);
}, function (failureResponse) {
deferred.reject({
error: 'Error while getting the data for the species list'
});
});
}
return deferred.promise;
}
}]);
for loop:
for (i=0;i<list.length;i++){
var linklist= APIService.getData(list[i]);
linklist.then(function (response) {
$scope.linkData = response;
console.log( $scope.linkData"") #1
}, function (response) {
console.log(response)
});
console.log( $scope.linkData"") #2
}
here first # 2 prints undefined based on list size and #1 prints the array based on list size any help? I know its async call but using promise also I cant sync it bcoz of for loop