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.")
}
});
}
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.
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.
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 , .
Callbacks are also closures as the passed function is executed inside other function just as if the callback were defined in the containing function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With