我正在使用带有$ http.get调用的角度工厂来返回包含所有总线及其depot和area属性的promise对象。
我遇到了以下代码的经典异步请求计时问题。 Console.log(allBuses)在console.log(depot)返回嵌套的$ http.get函数中的depot的名称之前返回一个空对象。
不使用setInterval或Timeout方法,如果为所有总线分配了depot和area属性,如何解析allBuses对象?
.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);
});
}])
答案 0 :(得分: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;
}])