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
}