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