我正在尝试从 WMS 图层返回时间值数组,我必须在 Openlayers 中填充下拉菜单。我已经能够在函数内的层中获取时间值列表(并将此输出打印到函数中的控制台),但无法从函数中获取此数组。当前代码如下:
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);
}
为了确认下拉菜单正常工作,我使用手动定义的时间集进行了测试。我只是不明白为什么函数没有返回列表“times”。
为了清楚起见,我对 javascript 比较陌生,但一般不会编码,所以如果有一个非常简单的解决方案,我深表歉意。我花了最后一个小时浏览 StackOverflow 问题,但找不到准确回答此问题的问题。
最佳答案
fetch 是异步操作的,因此所有依赖于从 url 读取的文本的处理都应该在 fetch 的最后一个 then
子句中。
另一种选择(并非所有浏览器都支持)是声明异步调用函数并使用await 语句
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');
关于javascript - 从获取的 WMS GetCapability 请求返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57725048/