I have a function that return a undefined thing even if it normally need to return something defined.
I have this code with a function :
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 }
and want to call it in an other files,
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);
});
But it always say undefined.
2
Answers
Because it was written in the definition: var answer
But using in :()
so it will be undefied,because you have not define answser, change "answser" to "answer" it will be fixed
The return statement you have inside the forEach will return from the closure, not the calling function.
One approach is to use a straightforward
for-of
loop instead of aforEach
call: