-1

I have a problem with the persistance of a variable in Node.js.

I make this routine:

var travelTimes;
for(var i = 0; i < data.length; i++){
    distance.get(
    {
        origin: hotel, 
        destination: data[i].ubicacion,
        language: 'es'
    },function(err, maps_data) {
        if (err) return console.log(err);
        travelTimes.push(data.ubication);
    });
}
console.log(travelTimes);

And the last line gives me undefined. I was searching and found it that because Node.js is asynchronous my variable maps_data only lives into the distance.get() callback, but I need that data to continue with my work. How can I make it live in all my code? Thanks!!

1 Answers1

0

How do I use a variable outside of a callback?

You can't.
The variable is defined inside of that callback and that callback only.
This is why it is logging undefined.

You could fix it by putting the console.log() inside of your function.

var travelTimes;
for(var i = 0; i < data.length; i++){
    distance.get(
    {
        origin: hotel, 
        destination: data[i].ubicacion,
        language: 'es'
    },function(err, maps_data) {
        if (err) return console.log(err);
        travelTimes.push(data.ubication);
        console.log(travelTimes); // Now it's inside the callback
    });
}
baranskistad
  • 2,176
  • 1
  • 21
  • 42