You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WMS遍历getFeatureInfo请求URL数组获取响应返回值顺序随机如何解决

问题原因

你遇到的返回值顺序随机问题核心是fetch属于异步网络请求:

  • 循环中同时发起的5个请求是并发执行的,服务器响应顺序不受请求发起顺序控制,哪个请求先完成返回,对应的then回调就先执行,就会先把值push进value数组,最终数组顺序自然是随机的。
  • 另外你现在直接在循环结束后就console.log(value),此时大概率还有请求未返回,你看到的数组其实是浏览器控制台异步刷新后的结果,不是循环结束那一刻的真实值。

修复方案

使用Promise.all来处理并发请求,它会严格按照你传入的请求顺序返回结果,不受各个请求的响应速度影响:

// 替换原来的循环发请求+push值的逻辑
// 生成promise数组,顺序和urlArray前5个元素的顺序完全对应
const requestPromises = [];
for (i = 0; i < 5; i++) {
  const url = urlArray[i];
  if (url) {
    requestPromises.push(
      fetch(url)
        .then(response => response.json()) // 直接调用内置的json()方法无需手动parse
        .then(jsonObject => jsonObject.features[0].properties.year)
    );
  } else {
    // 空url填充占位值,保证数组长度和顺序稳定
    requestPromises.push(Promise.resolve(null));
  }
}

// 等待所有请求全部完成
Promise.all(requestPromises)
  .then(value => {
    // 此处拿到的value数组顺序和urlArray前5个的顺序完全一致
    console.log(value);
    // 填充表格的逻辑写在这里
  })
  .catch(err => {
    // 统一处理请求异常
    console.error('请求出错:', err);
  });

额外优化建议

你当前生成35个URL的代码重复度很高,可以用双层循环简化,可读性和可维护性更好:

const yearArray = [1990, 1995, 2000, 2005, 2010, 2015];
const codeArray = [1,2,3,4,5,6,7];
const urlArray = [];
const baseUrl = sourceValues.getFeatureInfoUrl(
  evt.coordinate,
  viewResolution,
  'EPSG:3857',
  {'INFO_FORMAT': 'application/json'},
  {'VIEWPARAMS': 'code:1;year:1990'}
);
for (const code of codeArray) {
  for (const year of yearArray) {
    const currentUrl = baseUrl.replace(/year%3A\d+/, `year%3A${year}`).replace(/code%3A\d+/, `code%3A${code}`);
    urlArray.push(currentUrl);
  }
}

内容的提问来源于stack exchange,提问作者account28100210

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:45:01