I'm trying to return an array of time values from a WMS Layer I have to populate a dropdown menu in Openlayers. I have been able to get a list of time values in the layer inside a function (and print this output to the console in the function), but cannot get get this array out of the function. Current code is below:
var url = **working_WMS_url**
var GetCaps = new ol.format.WMSCapabilities();
fetch(url).then(function(response) {
return response.text();
}).then(function(text) {
var result = GetCaps.read(text);
var times = result.Capability.LayerLayer[0].Dimension;
return times;
});
console.log(times);
// Section below links and populates dropdown menu
var time_list = document.getELementById("time_list");
for(var i = 0; i < times.length; i++) {
var opt = times[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
time_list.appendChild(el);
}
To confirm, the dropdown menu works correctly, I tested with a manually defined set of times. I just can't work out why the list "times" isn't returned from the function.
For clarity, I am relatively new to javascript but not coding in general so apologies if there is a very simple solution to this. I've spent the last hour looking through StackOverflow questions but couldn't find one that answered exactly this problem.
fetch operates asynchronously so all processing which depends on the text having been read from the url should be in the final then
clause of the fetch.
An alternative (not supported on all browsers) is to declare the calling function asynchronous and use an await statement
async function myFunction(url, elementId) {
var GetCaps = new ol.format.WMSCapabilities();
var times = await fetch(url).then(function(response) {
return response.text();
}).then(function(text) {
var result = GetCaps.read(text);
console.log(result);
var times = result.Capability.Layer.Layer[0].Dimension;
return times;
});
console.log(times);
// Section below links and populates dropdown menu
var time_list = document.getElementById(elementId);
for(var i = 0; i < times.length; i++) {
var opt = times[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
time_list.appendChild(el);
}
}
myFunction('working_WMS_url', 'time_list');