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

异步函数getTGVStops始终返回undefined问题求助

异步函数getTGVStops调用返回undefined的问题排查与修复

核心问题点

  • 函数未返回目标值:原函数定义了answer变量,但整个函数没有任何return语句,async函数默认会返回undefined。
  • 变量拼写错误:在forEach循环里把answer写成了answser(多了一个s),导致实际赋值的是未声明的全局变量,而非初始定义的answer。
  • forEach无法中断循环:forEach中的return仅跳出当前迭代,不会终止整个循环,即使找到匹配的entity,后续仍会继续遍历,且无法直接通过forEach返回结果。

修复后的getTGVStops函数

const GtfsRealtimeBindings = require("gtfs-realtime-bindings");
const fetch = require("node-fetch");
const long = require("long");

async function getTGVStops(tgv_number){
    try {
      const response = await fetch("https://proxy.transport.data.gouv.fr/resource/sncf-tgv-gtfs-rt-trip-updates", {
        headers: {
          //"x-api-key": "<redacted>",
          // replace with your GTFS-realtime source's auth token
          // e.g. x-api-key is the header value used for NY's MTA GTFS APIs
        },
      });
      if (!response.ok) {
        const error = new Error(`${response.url}: ${response.status} ${response.statusText}`);
        error.response = response;
        throw error;
      }
      const buffer = await response.arrayBuffer();
      const feed = GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(
        new Uint8Array(buffer)
      );
      // 使用find定位第一个匹配的entity,直接返回目标数据
      const targetEntity = feed.entity.find((entity) => entity.id.includes(tgv_number));
      // 找到则返回站点信息,未找到返回null
      return targetEntity ? targetEntity.tripUpdate.stopTimeUpdate : null;
    }
    catch (error) {
      console.log(error);
      // 抛出错误让调用方处理,避免直接终止进程
      throw error;
    }
}

module.exports = { getTGVStops }

调用代码(新增异常捕获)

const tgv = require("./tgv_information.js")
const station = require("./station.js")
const GtfsRealtimeBindings = require("gtfs-realtime-bindings");

tgv.getTGVStops("6033").then((answer) => { 
    console.log("test")
    console.log(answer); 
}).catch(err => {
    console.error("获取站点信息失败:", err);
});

修复说明

  1. 移除冗余的answer变量,用find替代forEach,既能中断循环提升效率,又能直接获取匹配结果。
  2. 修正变量拼写错误,确保赋值操作作用于正确变量。
  3. 移除process.exit(1),改用throw error让调用方处理异常,避免直接终止整个程序。
  4. 调用代码新增catch块,处理异步函数抛出的异常,增强代码健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:57:19