I'm struggling to run this in a sequential manner. I've experimented with various methods like using Promise.all and getting stuck in callback hell, but what I really need is to obtain elevations for each point that has a valid altitude value (not -1) and wait until all of them have been set.
Extra credit for optimizing the code to only call google.maps.ElevationService.prototype.getElevationForLocations() once with a filtered list of points where altitude is not -1.
public async calculateElevations(): Promise<void> {
let counter = 0;
console.warn(counter++, 'start');
await this.$instructions.forEach(async (instruction) => {
console.warn(counter++, 'topForEach');
if (instruction instanceof PosInstruction && instruction.$alt === -1) {
const requestPoint: google.maps.LocationElevationRequest = { locations: [instruction.$latLng] };
await google.maps.ElevationService.prototype.getElevationForLocations(requestPoint, async (results: google.maps.ElevationResult[], status) => {
if (status === google.maps.ElevationStatus.OK) {
console.warn(counter++, 'status ok');
instruction.setAltitude(results[0].elevation);
}
else throw new Error(`calculateElevations() -- ${status.toString()}`);
});
console.warn(counter++, 'after getElevation');
}
});
console.warn(counter++, 'done');
}