Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  165] [ 3]  / answers: 1 / hits: 17181  / 11 Years ago, thu, october 3, 2013, 12:00:00

After hours of search, I Have a problem with my code Below.
In fact, I'm not very far from answer I think but I'm still blocked…



I have an anonymous function called inside a loop and I want to access and refresh global variables but I tried with window.myvariable, with another function and nothing happen…



this my code :



for (var i = 0; i < SHP_files.length; i++) {
shapefile = new Shapefile({
shp: shp/polygon/+SHP_files[i]+.shp,
dbf: shp/polygon/+SHP_files[i]+.dbf,
}, function(data) {

polygon_layer.addLayer(new L.GeoJSON(data.geojson,{onEachFeature: onEachFeature, style: polygonStyle}));
polygon_layer.addTo(map);
console.log(polygon_layer.getLayers()); // IS OK
});
};
console.log(polygon_layer.getLayers()); // IS EMPTY !!


So, How i could transform this anonymous function in order to have something that I can access from my code who's following that ?



Thanks a lot, and sorry for my english not very good…


More From » function

 Answers
193

This is your typical problem with asynchronous code execution. You example code does NOT execute from top to bottom. In particular, your anonymous function does NOT get executed until Shapefile is done with whatever it is doing. In the meantime, your JS gets executed in order. Therefore, the last line of your above code, will probably execute before the anonymous function ever will.



To fix this, you will need to trigger any code that depends on the Shapefile response from within its callback:



for (var i = 0; i < SHP_files.length; i++) {
shapefile = new Shapefile({
shp: shp/polygon/+SHP_files[i]+.shp,
dbf: shp/polygon/+SHP_files[i]+.dbf,
}, function(data) {
polygon_layer.addLayer(new L.GeoJSON(data.geojson,{onEachFeature: onEachFeature, style: polygonStyle}));
polygon_layer.addTo(map);
executeMoreCode();
});
};

function executeMoreCode() {
console.log(polygon_layer.getLayers()); // IS OK
}

[#75245] Wednesday, October 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
berenices

Total Points: 104
Total Questions: 106
Total Answers: 106

Location: Spain
Member since Thu, Dec 23, 2021
2 Years ago
;