我有一個configs
對象。對於configs
中的每個對象,我正在循環並使用$ http.get(它位於SPARQLService中)執行調用。 configs
對象包含不同的對象,因此對不同的URL進行不同的調用。在那個循環中,無論何時我從$ http.get獲得承諾,在then
函數中,我正在更新$ rootScope中找到的對象。我得到的問題是configs
包含不同的對象,但是我在rootScope中更新的對象都包含與configs
類似的對象的結果。示例代碼:AngularJS Promise Loop error
for (var config in configs){
var newConfig = configs[config];
var data = SPARQLService.query(newConfig["endpointURL"],encodeURIComponent(newConfig["SPARQLQuery"]));
var bindings;
data.then(function (answer){
sparql_result = answer.data;
bindings = answer.data.results.bindings;
//creating the markers
markers = [];
for (var binding in bindings){
currentBind = bindings[binding];
var latitude = currentBind[newConfig["lat"]].value;
var longitude = currentBind[newConfig["long"]].value;
var currentMarker = L.marker([latitude, longitude]);
currentMarker.bindPopup(Utilities.generateDescription(newConfig["desc"],currentBind));
markers.push(currentMarker);
}
$rootScope.config[newConfig["groupName"]] = newConfig;
$rootScope.layers[newConfig["groupName"]] = L.layerGroup(markers);
console.log($rootScope.config);
},
function (error){
});
}
認爲你的問題可能是'var newConfig'聲明在循環中引用它的函數之外。 'newConfig'將在循環的每次迭代中更新,但對它的引用用於異步觸發的函數中,相信它們在執行時都會引用相同的'newConfig' ...將用具有斷點的調試器,其中newConfig用於將事物分配給$ rootScope。 – shaunhusain
但爲什麼newConfig對象引用configs中的最後一個對象? – Noor
嗯,我想到的是,當你做.then調用你給它一個新的函數來調用將來的某個時候,但它不會執行正確的時候,你繼續循環和更新newConfig,直到你完成循環遍歷所有的配置,並在那一刻newConfig指向最後一件事情,現在異步http調用完成,堆棧的回調函數開始觸發。 – shaunhusain