gpt4 book ai didi

javascript - AngularJS Promise 循环错误

转载 作者:行者123 更新时间:2023-12-02 14:10:40 25 4
gpt4 key购买 nike

我有一个configs对象。对于 configs 中的每个对象,我使用 $http.get(位于 SPARQLService 中)循环并执行调用。 configs 对象包含不同的对象,因此对不同的 URL 进行不同的调用。在该循环中,每当我从 $http.get 获得 promise 时,在 then 函数中我都会更新 $rootScope 中找到的对象。我遇到的问题是 configs 包含不同的对象,但我在 rootScope 中更新的对象都包含来自 configs 的类似对象的结果。示例代码:

 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){

});

}

最佳答案

我认为你的问题是 then 函数中的 newConfig 通过引用绑定(bind)到 newConfig 的值,所以当 promise 完成时执行它将采用当时 newConfig 中的任何值 - 而不是在调用 Promise 时。

每次执行外循环时:

for (var config in configs ){
var newConfig = configs[config];

newConfig 将收到一个新值,但它不是一个新变量 - 在 JavaScript 中 for 循环不是变量的作用域,因此 newConfig 实际上属于 for 循环之外的范围,即使它是在其中声明的。当您的 then 函数访问 newConfig 时,它正在访问当前驻留在此“全局”newConfig 中的值,该值可能是来自最终的值循环的迭代(假设服务调用需要足够长的时间才能在 Promise 返回之前完成循环)。

您需要以某种方式通过服务调用传递它,以便它在 then 函数的 answer 内容中可用。

关于javascript - AngularJS Promise 循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39621350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com