Utilizing Async/Await to Streamline Google Maps Elevation Requests

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');
}

Answer №1

Trying to use await getElevationForLocations won't work because it doesn't return a Promise. Instead, it triggers a callback upon completion which can be wrapped in a Promise:

public async encodeElevations(): Promise<void> {
    let x = 0
    console.warn(x++, 'start')
    const instructions = this.$instructions.filter(ins => ins instanceof PosInstruction && ins.$alt === -1);
    const promiseArray = instructions.map((ins) => {
      console.warn(x++, 'topForEach')
      const reqPoint: google.maps.LocationElevationRequest = { locations: [ins.$latLng] }
      return new Promise((resolve, reject) => {
        google.maps.ElevationService.prototype.getElevationForLocations(reqPoint, (results: google.maps.ElevationResult[], status) => {
          if (status === google.maps.ElevationStatus.OK) {
            console.warn(x++, 'status ok')
            ins.setAlt(results[0].elevation)
            resolve(ins);
          } else {
            reject(new Error(`encodeElevations() -- ${status.toString()}`));
          }
        });

        console.warn(x++, 'after getElev')
      });
    })

    const array = await Promise.all(promiseArray);

    console.warn(x++, 'done')
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error occurred while defining props due to a parsing issue with the prop type. The unexpected token was encountered. Perhaps you meant to use `{`}` or `}`?

const dataProps = defineProps({ selectedData: <Record<string, string>> }); Under the closing bracket, there is a red line indicating: Error: Unexpected token. Consider using {'}'} or &rbrace; instead?eslint Expression expecte ...

A guide on capturing the response in the POST method within Angular 7

I'm currently working with Angular 7 and I need a way to know if the data has been successfully saved or not. Within my web service code, I have designated "Success" as the status when data is saved correctly, and "Unsuccessful" if the data is not sa ...

TSLint warning: Duplicate identifier detected - 'err'

Currently facing an issue with tslint displaying the following error Shadowed name: 'err' Providing the code snippet for reference fs.readdir(fileUrl, (err, files) => { fs.readFile(path.join(fileUrl, files[0]), function (err, data) ...

Accessing URL fragments in Next JS with context during the execution of getServerSideProps

I am trying to extract a URL fragment using getServerSideProps. The URL is structured like this: http://localhost:3000/some-folder#desiredParam=value Even though I pass the context as an argument to the getServerSideProps function, I am struggling to retr ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Sending an array of data using Angular in a web service

Here is my model object from model.ts name_id: string[]; public generateUrlencodedParameters(token: string, id?: number): string { let urlSearchParams = new URLSearchParams(); urlSearchParams.append('name_id', this.name_id.toS ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

Implement Php gettext functionality in Typescript

I have a keen interest in AngularJs 2, and I am planning to incorporate it into my upcoming project. I would like to integrate i18n with Php gettext. In a previous project, I utilized Php gettext by embedding Php within Javascript code as shown below: // ...

Is it possible to achieve pagination by simply dragging the scroll bar to the top or bottom position?

Recently, I've been working on implementing a pagination function for a list of items. The pagination currently works well with scrolling events - it automatically moves to the next page when scrolling to the bottom, and to the previous page when scro ...

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

TypeScript encountered an error: The get call is missing 0 type arguments

I encountered a typescript error stating "Expected 0 type arguments, but got 1" in the line where my get call is returning. Can you help me identify what is wrong with my get call in this code snippet? public get(params: SummaryParams): Observable&l ...

Issue with page break functionality during print preview

div.pagebreak { page-break-after: always; page-break-inside: avoid; } HTML <!-- Page separator --> <div class="pagebreak" style="float: none;"><hr class="hidden-print" /></div> <app-mud-chec ...

Mapping the preselected values of multiple input fields into an array in Angular 6: A step-by-step guide

When submitting a form with input fields, I need to capture the selected values into an array format like {"userid":1,"newstatus":[1],"mygroup":[1,2,3]}. I attempted using ngmodel but encountered issues. Below is the code snippet: home.component.html & ...

Problems encountered when utilizing $in operator in Mikro ORM MongoDB operations

For my project, I'm utilizing mikro orm with MongoDB to handle database operations in TypeScript. So far, it has proven to be the most effective ORM for MongoDB in this language. However, I've encountered type errors when using $in with Object ID ...

The saved editable input number is automatically pushed even without needing to click on save or cancel

I am working with a datatable, chart, and a label that shows the latest added value. The table and chart display time-series data for the last 30 minutes, including the timestamp and a random numerical value between 0 and 999. Every 10 seconds, a new data ...

Error message: "Unable to find a windows instance" encountered while conducting tests on Paho MQTT Client using mocha and typescript

After spending countless days searching online, I have yet to find any resources on testing the Paho MQTT Client. My approach so far has been somewhat naive, as shown below: import { suite, test, slow, timeout, skip, only } from 'mocha-typescript&apo ...

When faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

Creating a constant.ts file to define universal constantsWould you like assistance with anything else

Is there a way to create a constant.ts file or use a command to declare all global constants and export them for easy access? ...

How come Asyncio fails to decrease the total execution time in Python when attempting to run functions simultaneously?

I have been experimenting with running code using asyncio in order to reduce the overall execution time. The code I have written currently takes about 6 seconds to complete. Here is the code snippet: Traditional Function Calls- (Method 1) from time import ...

When using the `create-react-app` command with the `--typescript` flag, you may encounter an issue when attempting to compile namespaces with the `--

I started a project using npx create-react-app my-app-ts --typescript, then I added two new files, sw-build.js and sw.js in the src/ directory. The content of these files was taken from the discussion on Workbox guidelines at (Guidlines for Using Workbox) ...