我有一个函数,即使它通常需要返回已定义的东西,也会返回未定义的东西。
我有这个带有函数的代码:
const GtfsRealtimeBindings = require("gtfs-realtime-bindings");
const fetch = require("node-fetch");
const long = require("long");
async function getTGVStops(tgv_number){
var answer
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;
process.exit(1);
}
const buffer = await response.arrayBuffer();
const feed = GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(
new Uint8Array(buffer)
);
feed.entity.forEach((entity) => {
if (entity.id.includes(tgv_number)) {
answser = entity.tripUpdate.stopTimeUpdate
console.log(answser)
return answser
}
})
}
catch (error) {
console.log(error);
process.exit(1);
}
}
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);
});
但总是说未定义。
因为定义里写的是: var answer 但用在:()
if (entity.id.includes(tgv_number)) {
answser = entity.tripUpdate.stopTimeUpdate
console.log(answser)
return answser
}
这样就无法确认了,因为你还没有定义answser,把“answser”改为“answer”就可以解决了
forEach 中的 return 语句将从闭包返回,而不是调用函数。
一种方法是使用简单的
for-of
循环而不是 forEach
调用:
for (entity of feed.entity) {
if (entity.id.includes(tgv_number)) {
answser = entity.tripUpdate.stopTimeUpdate
console.log(answser)
return answser
}
}