Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - how to work with the iterator in a for loop with callbacks

I am trying in the for loop to access the value of the i with which the callback function uses.

How can I do this?

for (var i = 0; i < a.length; i++)
{
    calcRoute(fixedLocation, my_cities[i].address, function(response) {

        // i want here to have the current "i" here

    });             
}

which calls...

function calcRoute(x, y, callback) {

    var start = x;
    var end = y;

    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        optimizeWaypoints: true
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            callback(response);                                                                 
        } else {
            alert("City unknown.")
        }       
    }); 
}
like image 379
Valentin Despa Avatar asked Feb 21 '12 12:02

Valentin Despa


People also ask

Can a callback function be async?

Asynchronous callbacks are functions passed to another function that starts executing code in the background. Typically, when the code in the background finishes, the async callback function is called as a way of notifying and passing on data to the callback function that the background task is finished.

Are callbacks synchronous?

The function that takes another function as an argument is called a higher-order function. According to this definition, any function can become a callback function if it is passed as an argument. Callbacks are not asynchronous by nature, but can be used for asynchronous purposes.

What is the difference between a promise and a callback in the context of asynchronous code?

The TL:DR - version: Callbacks are functions passed as arguments into other functions to make sure mandatory variables are available within the callback-function's scope. Promises are placeholder objects for data that's available in the future. As soon as their state changes from pending to resolved , .

Is callback a closure?

Callbacks are also closures as the passed function is executed inside other function just as if the callback were defined in the containing function.


1 Answers

It's because the closure captures the variable i itself, not the current value. Try:

for (var i = 0; i < a.length; i++) (function(i)
{
    calcRoute(fixedLocation, my_cities[i].address, function(response) {

        // i want here to have the current "i" here

    });             

}) (i);

which will create a new i variable for each loop iteration.

like image 143
James McLaughlin Avatar answered Oct 19 '22 22:10

James McLaughlin