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

为何我的查询函数返回Promise {<pending>}而非预期的企业条目数据

核心问题
  • 遍历企业列表调用异步距离计算方法时,未使用Promise.all等待所有异步任务执行完成,直接返回了未完成状态的Promise数组
  • 距离计算完成后的筛选逻辑错误:无需重复查询企业表,直接基于已查询到的企业对象做距离判断即可,原有代码中的knex查询既无返回也未执行
  • 距离单位转换逻辑不严谨:谷歌距离接口返回的distance.value默认单位为米,直接除以1000即可转换为公里,字符串截取操作容易引发格式错误
代码修正

主查询逻辑修正

const getAllByDistance = async (location) => {
  // 第一步:查询所有企业数据
  const entries = await knex('companies').select();
  // 第二步:批量计算所有企业和目标位置的距离,等待所有异步计算完成
  const companiesWithDistance = await Promise.all(
    entries.map(async (company) => {
      const distanceInMeter = await getDistance(location, `${company.street}, ${company.postcode} ${company.place}`);
      return {
        ...company,
        distance_km: distanceInMeter / 1000
      };
    })
  );
  // 第三步:过滤出符合距离要求的企业
  return companiesWithDistance.filter(company => company.maximum_distance_km >= company.distance_km);
};

距离计算方法兼容优化

const getDistance = async (loc1, loc2) => {
  const origins = encodeURI(`?origins=${loc1}`);
  const destinations = encodeURI(`&destinations=${loc2}`);
  const key = `&key=${process.env.VUE_APP_GOOGLE_MAPS_API_KEY}`;
  const config = {
    method: 'get',
    url: `https://maps.googleapis.com/maps/api/distancematrix/json${origins}${destinations}${key}`,
    headers: {}
  };
  try {
    const response = await axios(config);
    const element = response.data.rows[0].elements[0];
    // 兼容地址无效、无可行路线的场景
    if (element.status !== 'OK' || !element.distance) return Infinity;
    return element.distance.value;
  } catch (err) {
    console.log('距离接口调用失败', err);
    return Infinity;
  }
}

原有接口调用代码无需修改,修改后返回结果即为符合距离要求的企业数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:15:04