1

I'm working with ajax and google maps. I want to create (and refresh after) markers on my maps with async call.. that's my code:

function createMarker(){
    for (var i in selectedTrucks) {

    var urlReq = '/ajaxRequest/getSingleTruckPosition/' + selectedTrucks[i];
    console.log("Launching createMarker() request on: " + urlReq);

    $.ajax({
        url: urlReq,
    })
    .done(function(data) {

        var equipValue = jQuery.parseJSON(data);

        if(equipValue == null)
            console.log(selectedTrucks[i] + " has no position.");
        else{
            //console.log("Creating marker n° " + i + " on position: lat: " + equipValue.latitudine + " lng: " +  equipValue.longitudine);
            console.log("Creating marker n° " + i + " on position: lat: " + equipValue.LATITUDINE + " lng: " +  equipValue.LONGITUDINE);
            markers[i] = new google.maps.Marker({
                position: new google.maps.LatLng(equipValue.LATITUDINE,  equipValue.LONGITUDINE),
                map: map,
                //icon: iconBase + 'truck.png'
            });


            var infowindow = new google.maps.InfoWindow(); // popup marker 

            makeInfoWindowEvent(map, infowindow, "Marker: " + i, markers[i]);

            markers.push(markers[i]);

        }
    })
    .fail(function() {
        console.log("Ajax failed to fetch data on createmarker")
    })

}

}

Basically all works but, when I launch makeInfoWindowEvent() marker index is always the last of my for cycle. I Think is a problem with ajax callback with for. How can I stop the for cycle during ajax call?

There some await like c#? I am newbie with JS

eAbi
  • 3,220
  • 4
  • 25
  • 39
Aso Strife
  • 1,089
  • 3
  • 12
  • 31

1 Answers1

2

Your callback function (inside .done) is only and always called after the for loop is completed, because it is async.

Since you need the value of your index inside the callback, you need to wrap the ajax calls inside an immediately executing function, and pass it the index. Something like:

for (var i=0;i<length;i++){
  (function(i){

    //make all your async calls using `i`

   })(i);
}
Sidd
  • 1,389
  • 7
  • 17