0

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

  • `APIService.getData` is aysnc function, you can't get the result immediately back. – Pengyy May 04 '17 at 13:02
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – georgeawg May 04 '17 at 18:04
  • is their any way to stop the for loop iteration unless I get the response from the service? – monster_666 May 05 '17 at 09:25

0 Answers0