0

Is it possible to add a variable outside of a callback scope to the callback function itself?

For this specific case I'm trying to fire multiple Google Maps ElevationService queries but I only want to continue if all requests are completed. I'm in a for-loop with i as my current iteration and tried to bind it to the callback as so:

function getRouteElevationChartData(batchSize) {
    var elevator = new google.maps.ElevationService();

    for (var i = 0; i < totalElevationBatches; i++) {
        currentRouteElevationBatch = i;
        var thisBatchPath = [];

        for (var j = i * batchSize; j < i * batchSize + batchSize; j++) {
            if (j < directions.routes[0].overview_path.length) {
                thisBatchPath.push(directions.routes[0].overview_path[j]);
            } else {
                break;
            }
        }

        elevator.getElevationAlongPath({
            path: thisBatchPath,
            samples: 256
        }, function (elevations, status, i) {
            console.log('elevations: ' + elevations);
            console.log('status: ' + status);
            console.log('i: ' + i);

            if (status != google.maps.ElevationStatus.OK) {
                return;
            }

            onGetRouteElevationChartDataComplete(i, elevations);
        }(i));
    }
}

The problem is that elevations and status are no longer the Elevation Service's reponses... Is it possible to achieve what I want? Or can't this be done? Not sure how this should work. Thanks.

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129
  • If these queries work in async way I would suggest to use Promises: [native](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or third-party like jQuery's. – hindmost Mar 27 '16 at 09:34
  • They are async, that's why I need the iteration index to make sure all iterations have completed. Using a global variable to set the current i doesn't work because when call 1 isn't finished yet iteration 2 has already started resulting in a wrong result. I'll have a look at Promises. Thanks – Ben Fransen Mar 27 '16 at 09:51

0 Answers0