Obtener variable de la función de devolución de llamada

function foreignCoordinatesArray(){

  var coordinates = [];
  $.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);

  function success(ary) {
    for(var a in ary){
      var obj = ary[a];
      coordinates.push(new google.maps.LatLng(obj.latitude, obj.longitude));
    }

  }
  console.log(coordinates);
}

At the end coordinates will still be [] and not [{...},{...},...]. I guess this must be a problem with closures

How can I have my desired value in coordinates array?

preguntado el 12 de junio de 12 a las 22:06

try console.log inside success function -

3 Respuestas

It's not a problem with closures but with asynchronous nature of JavaScript AJAX calls. The moment AJAX call response arrives (and your success function is called, propagating coordinates array) it is way after you logged in that array - which was empty at that time.

I guess you want to somehow return the coordinates del foreignCoordinatesArray() function. As you can see you cannot use return:

function foreignCoordinatesArray(){
  var coordinates = [];
  $.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);

  function success(ary) {
    //...
  }
  return coordinates;
}

Instead you should pass a callback function that will receive coordinates:

function foreignCoordinatesArray(coordinatesCallback){
  var coordinates = [];
  $.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);

  function success(ary) {
    //...
    coordinatesCallback(coordinates);
  }
}

BTW you should escape $('#foreign_travel').val() before using it as part of the URL.

Respondido el 12 de junio de 12 a las 22:06

Thanks! that was what I was looking for. - David Rz Ayala

The problem isn't with "closures," per se, but with asynchronous programming. The success function won't be called until the JSON has been fetched, which will pretty much always be long after your foreignCoordinatesArray() function has returned. In general, when you're using an asynchronous function like $.getJSON(), any code outside the callback shouldn't assume the callback has already run, because that is not generally a safe assumption.

The solution in this case is to move your console.log(coordinates) en la función de éxito.

Respondido el 12 de junio de 12 a las 22:06

The callback is happening after the console.log() is executed. If you move console.log() into the callback function you should get the expected output.

function foreignCoordinatesArray(){

  var coordinates = [];
  $.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);

  function success(ary) {
    for(var a in ary){
      var obj = ary[a];
      coordinates.push(new google.maps.LatLng(obj.latitude, obj.longitude));
    }
    console.log(coordinates);
  }

}

Respondido el 12 de junio de 12 a las 22:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.