I am a javascript-noob trying to access data via geoserver and openlayers3. Here is my code:
function loadData(featureName)
{
var features = [];
var featureRequest = new ol.format.WFS().writeGetFeature({
srsName: 'EPSG:4326',
featurePrefix: 'progeo16',
featureTypes: [featureName],
outputFormat: 'application/json'
});
fetch('http://...:8080/geoserver/wfs', {
method: 'POST',
body: new XMLSerializer().serializeToString(featureRequest)
}).then(function(response) {
return response.json();
}).then(function(json) {
features = new ol.format.GeoJSON().readFeatures(json);
});
return features;
}
My problem is now, that the features-array won't be filled "fast" enough. If I set a breakpoint (using firebug) at "return features;" the array will be empty. If I wait 2 seconds and hover over the variable "features", the array is filled with the expected elements. So my question is: I think that may be a problem due to a asynchronous request. How can I be able to return the filled array in a proper way?
Thanks in advance
There might be delay in asynchronous call.One way to deal with it is call the next consecutive step only after the completion of the asynchronous call.I added callback_function() in your code. For example
function loadData(featureName,callback_function)
{
var features = [];
var featureRequest = new ol.format.WFS().writeGetFeature({
srsName: 'EPSG:4326',
featurePrefix: 'progeo16',
featureTypes: [featureName],
outputFormat: 'application/json'
});
fetch('http://...:8080/geoserver/wfs', {
method: 'POST',
body: new XMLSerializer().serializeToString(featureRequest)
}).then(function(response) {
return response.json();
}).then(function(json) {
features = new ol.format.GeoJSON().readFeatures(json);
callback_function(features);
});
}
Then make your function loadData() to return nothing. But when your asynchronous call fetches data, it will execute callback_function() which is the next steps of your logic.