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

ArcGIS Leaflet异步查询结果无法存入数组问题求助

问题分析与解决方法

你的判断完全正确,问题核心就是异步调用的时序冲突:

  • .query().nearby().run()是异步操作,循环会快速发起所有请求,但这些请求的回调逻辑要等后端返回数据后才会执行。而你的函数在所有异步请求还没返回结果时,就已经把空的nearbyCollection返回了。
  • 后续异步请求陆续完成后,才会往数组里push数据,这就是为什么控制台能看到数组内容,但调用length或遍历结果为空——这些操作是在函数返回后立刻执行的,早于异步请求的完成时机。

解决代码

把每个异步查询包装成Promise,用Promise.all()等待所有请求完成后再合并返回结果:

const queryFeature = async (e: any) => {
  const queryPromises = [];
  console.log(e);
  const latlngParcel = new L.Polygon(e);
  console.log(latlngParcel);

  for (let n = 0; n < e[0].length; n++) {
    const point = L.latLng(e[0][n]);
    // 将run的回调逻辑转为Promise
    const queryPromise = new Promise((resolve, reject) => {
      featureRef
        .query()
        .nearby(point, 1)
        .run((error: any, featureCollection: any) => {
          if (error) {
            console.log(error);
            reject(error);
          } else {
            // 提取当前查询的有效数据
            const currentFeatures = featureCollection.features.map((i: any) => ({
              id: i.id,
              name: i.properties.Situs1
            }));
            resolve(currentFeatures);
          }
        });
    });
    queryPromises.push(queryPromise);
  }

  try {
    // 等待所有查询完成,合并所有结果为一维数组
    const allResults = await Promise.all(queryPromises);
    return allResults.flat();
  } catch (error) {
    console.error('查询出错:', error);
    return [];
  }
};

使用说明

调用该函数时,需要通过await或.then()获取最终结果:

// 方式1:在async函数内使用await
async function processPolygon(e: any) {
  const nearbyFeatures = await queryFeature(e);
  console.log(nearbyFeatures.length); // 此时能拿到正确长度
}

// 方式2:用then回调处理结果
queryFeature(e).then(nearbyFeatures => {
  console.log(nearbyFeatures);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:50:36