0

I am using an angular factory with an $http.get call to return a promise object with all buses and their depot and area properties.

I am running into classic async request timing issues with the following code. Console.log(allBuses) returns an empty object before console.log(depot) returns the names of the depots in the nested $http.get function.

Without using setInterval or Timeout methods, how do I resolve allBuses object once all buses have been assigned depot and area properties?

.factory('busesByDepot', ['$http', 'Camelize', function($http, Camelize){

// get all depot data from depots object
return $http.get('data/depotList.json').success(function(data) {

    allBuses = {};

    data.data.forEach(function(depot){
        var camelName = Camelize.strToCamel(depot.name);
        if(depot.active == true){

            $http.get('data/'+ camelName +'.json').success(function(data) {
                data.forEach(function(d){
                    allBuses[d.num] = {depot: camelName, area: d.area};
                })
                console.log(depot);
            })
        }
    })
    console.log(allBuses);
});

}])
2
  • i've deleted my answer since i did not saw the outer forEach Commented Jul 13, 2015 at 16:46
  • the first solution that comes to my mind is creating a promise and resolving it after the foreach ends Commented Jul 13, 2015 at 16:46

1 Answer 1

0
.factory('busesByDepot', ['$http', 'Camelize', '$q', function($http, Camelize, $q){
var deferred = $q.defer();
// get all depot data from depots object
$http.get('data/depotList.json').success(function(data) {

    allBuses = {};
    inc = 0;

    data.data.forEach(function(depot){
        var camelName = Camelize.strToCamel(depot.name);
        if(depot.active == true){

            $http.get('data/'+ camelName +'.json').success(function(data) {
                data.forEach(function(d){
                    allBuses[d.num] = {depot: camelName, area: d.area};
                })
                inc++;
                if(inc ==2){
                    deferred.resolve(allBuses)
                };
            })

        }
    })

});

return deferred.promise;

}])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.