Geocode promise left unattended

After reviewing my code, I discovered that it is executing too quickly for use in the Angular template. Here is an excerpt of the problematic code:

this.dataService.getSomeData().subscribe(async (res) => {
  this.historyList = res;
  this.historyList.forEach(async (element) => {
    console.log('before')
    let address = await this.geocode(element);
    console.log(address)
    element.address = address
 });
 console.log('after');

The geocode promise function causing the issue looks like this:

async geocode(item:Location):Promise<string> {
   return await new Promise(async (resolve) => {
    const geocoder = new google.maps.Geocoder();
    const location = new google.maps.LatLng(item.latitude, item.longitude);
    geocoder.geocode({ location: location }, async (results, status) => {
      if (status === 'OK') {
        resolve(results[0].formatted_address);
      }
    });
  });
 }
  

Currently, "Before" logs multiple times and the "After" log appears before any addresses are returned. I'm unsure where the problem lies; VS Code doesn't indicate any issues with the await on the geocode method.

Any insights would be greatly appreciated. Thanks

Answer №1

When utilizing .forEach(async element=>, it does not wait on the callbacks. To execute them sequentially, consider using a for-of loop:

this.dataService.getSomeData().subscribe(async (res) => {
  this.historyList = res;
  for(const element of this.historyList) {
    console.log('before')
    let address = await this.geocode(element);
    console.log(address)
    element.address = address
  }
  console.log('after');
}

To perform the tasks concurrently, you can utilize Promise.all:

this.dataService.getSomeData().subscribe(async (res) => {
  this.historyList = res;
  // use map to create a promise for each element.
  await Promise.all(this.historyList.map(async (element) => {
    console.log('before')
    let address = await this.geocode(element);
    console.log(address)
    element.address = address
 }));
 console.log('after');
}

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

Caution: The `id` property did not match. Server: "fc-dom-171" Client: "fc-dom-2" while utilizing FullCalendar in a Next.js environment

Issue Background In my current project, I am utilizing FullCalendar v5.11.0, NextJS v12.0.7, React v17.0.2, and Typescript v4.3.5. To set up a basic calendar based on the FullCalendar documentation, I created a component called Calendar. Inside this comp ...

Angular route fails to load the HTML file

In the process of developing a route within an Angular application, I have successfully implemented 3 routes. However, one particular route is giving me trouble. I have three folders that need to redirect HTML based on the option chosen. In Angular, I cre ...

Performing actions simultaneously with Angular 2 directives

My custom directive is designed to prevent a double click on the submit button: import { Directive, Component, OnInit, AfterViewInit, OnChanges, SimpleChanges, HostListener, ElementRef, Input, HostBinding } from '@angular/core'; @Directive({ ...

In order to retrieve specific object attributes using the unique identifier

I am currently managing 2 API's referred to as teachers and sessions. The contents of the teachers JSON file are: [ { "teacherName": "Binky Alderwick", "id": "01" }, { "teacherName": "Basilio Gregg", ...

Can you show me the steps for linking the next method of an EventEmitter?

After emitting an event, I am looking to run some additional code. Is there a method to chain the .next() function in this way? @Output() myEvent = new EventEmitter<string>(); this.myEvent.next({‘test string’}).onComplete(console.log('done& ...

Using the VSCode debugger to place a breakpoint within a Typescript package that has been symlinked using `npm link`

I'm currently troubleshooting a NodeJS application and its associated typescript packages, which have been linked using `npm link`. The directory structure is as follows: /root/package-a # typescript package /root/package-b # another typescript packa ...

Angular/NestJS user roles and authentication through JWT tokens

I am encountering difficulties in retrieving the user's role from the JWT token. It seems to be functioning properly for the ID but not for the role. Here is my guard: if (this.jwtService.isTokenExpired() || !this.authService.isAuthenticated()) { ...

Executing the outer function from within the inner function of a different outer function

Imagine this scenario: function firstFunction() { console.log("This is the first function") } secondFunction() { thirdFunction() { //call firstFunction inside thirdFunction } } What is the way to invoke firstFunction from thirdFunction? ...

Uncertainty regarding the integration process of `create-react-app --template typescript` with typescript-eslint

After creating a react project using npx create-react-app my-app --template typescript, I was surprised to find that typescript-eslint was already enabled by default. https://i.sstatic.net/1uijf.png Upon inspecting the eslint config within the package.jso ...

Employing a section of an intricate map found in the Stores React platform

Take a look at this data stored in Zustand or any other store. productMap: { 'product-id-abc': { info: { name: 'Gmail', url: 'gmail.com', api: 'localhost:8080' }, endpo ...

Getting Typescript Compiler to Recognize Global Types: Tips and Strategies

In the top level of my project, I have defined some global interfaces as shown below: globaltypes.ts declare global { my_interface { name:string } } However, when attempting to compile with ts-node, the compiler fails and displays the er ...

GlobalsService is encountering an issue resolving all parameters: (?)

I am currently working on implementing a service to store globally used information. Initially, the stored data will only include details of the current user. import {Injectable} from '@angular/core'; import {UserService} from "../user/user.serv ...

Checking if a route path is present in an array using Typescript and React

Here is a sample of my array data (I have simplified it here, but there are approximately 100 elements with about 20 values each): 0: odata.type: "SP.Data.ProductListItem" Title: "This is Product 1" Id: 1 1: odata.type: "SP.Data.ProductListItem" Title: ...

Angular Material - Implementing pagination for a dynamic table

I'm facing a challenge with my Angular Material dynamic table, as I am fetching data from an external database using an API. I am attempting to implement pagination on the table, but I can't seem to find suitable examples that match my scenario. ...

In React + TypeScript, learn how to effectively pass down a function from a container component to a

I am currently working on developing a tabs application using React and Typescript. The main component, Tabs, manages the state and passes it down to the Content component. Additionally, I have implemented a function called 'handleName' which is ...

When using Array.find() in TypeScript, the Subscribe function does not get called

I am currently diving into Typescript and web development, but I've encountered a peculiar issue when subscribing to an event that's leaving me stumped. In my service, I'm using a BehaviorSubject to store a carId, and on a page where there&a ...

Experiencing a useContext error when implementing MDX with NextJS 13

I am currently working on integrating mdx files into Next.js 13. After completing all necessary configurations in next.config and creating the file structure, I have the following path within the app folder: > docs > components > accordion > pa ...

Incorporate a personalized Cypress function for TypeScript implementation

I'm in the process of developing a custom cypress command that will enable me to post a file using formData, as the current cy.request does not yet support formData. For the actual POST operation, I am utilizing request-promise-native. To begin with ...

What is the best way to implement typing in getServerSideProps using Next.js with TypeScript?

I'm currently working on a project using NextJs and TypeScript, but I've encountered an issue with types in the getServerSideProps function. In my code snippet for getServerSideProps, I am retrieving data using context.query. However, despite my ...

When building websites, pages, or applications with React, how do you determine the best choice between JavaScript, TypeScript, or JavaScriptXML?

After completing my portfolio and an eCommerce website design using Figma, I started learning React and Tailwind with Vite. I'm comfortable with basic JavaScript but now I want to understand the differences between .js, .jsx, and .ts files when workin ...