implement a promise within the array elements contained in a Map instance

Iterating over a Map object involves processing a collection of Polygons, where each Polygon is represented by a set of coordinates including latitude and longitude. The goal is to perform an asynchronous action on each coordinate within the Map (Polygon) that returns a Promise. Upon completion of the Promise, which results in a string, it should be added to an array with "POLYGON..." preceding it. Once all iterations over the Map are finished, there will be an array containing "Polygons" along with their respective coordinates. This array will then be used for further actions. However, a problem arises as the Map iteration completes without accounting for the Promises within it. This means that the array intended to store the results of these Promises remains undefined when the iteration finishes. The code snippet displays this process:

//Polygons represents the Map object
let polygonsarray : [] = []
let strPolygonArray : string;
for (let [key, value] of this.Polygons.items.entries())
{
    if (value.PolygonItem)
    {
        Promise.all(value.PolygonItem.map(p =>
        {
            return someAsychActionThatReturnPromise(p).then(res => res)
        })).then(data =>
        {
            polygonsarray.push("POLYGON(" + data + ")");
            
        }).catch(err => throwError(err));
    }
}

//the polygonsarray still remains empty at this stage
strPolygonArray = polygonsarray.join();

Answer №1

Make sure you are patient and waiting for the Promise.all().then() promise to fully resolve before proceeding. Printing should be done once everything is successfully executed.

Consider the following points:

  • The .then(res => res) method simply duplicates a promise without adding any real value.

  • Using err => return throwError(err) is not valid JavaScript syntax. Instead, pass throwError as a reference function in the catch callback.

  • When adding elements to an array asynchronously, return the promised values to be pushed. After all promises resolve with Promise.all, collect the data into the array at once.

  • Opt for using async await syntax for improved code readability.

  • If you're not using the keys from entries(), prefer utilizing values() instead.

Below is a revised snippet (error handling excluded):

async collectPolygons() {
    let polygonsarray : [] = await Promise.all(
        Array.from(this.Polygons.items.values(), async ({PolygonItem}) => {
            if (!PolygonItem) return ""; // To be filtered later
            let data = await Promise.all(PolygonItem.map(someAsychActionThatReturnPromise));
            return "POLYGON(" + data.join(",") + ")";
        }) 
    );
    
    let strPolygonArray : string = polygonsarray.filter(Boolean).join(",");
    // ...
}

If your context involves a class method, prefix the method name with async. For standalone functions, add the function keyword as well.

Note that strPolygonArray will be assigned a value asynchronously. Thus, callers must use asynchronous patterns like await or then to access the actual value.

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

Resolve a function dynamically by utilizing a mapping of records

I am looking to run a specific handler for an input based on the type property of the input. The setup is as follows: type MyObjectType = "alpha" | "beta"; interface MyAlphaObject { value: number; type: "alpha"; } interf ...

Universal NestJS GraphQL Guard

I am currently working on implementing a global guard to ensure that all requests receiving MUTATIONS from graphql require the token in their headers by default. The code below successfully achieves this: graphql-context-get-token.guard.ts import { ...

Updating content in Angular 2 using PUT method with the "uri/list" content type for multiple elements

What is the process for sending multiple elements in a PUT request using Angular 2 and Typescript? In order to send multiple URIs, they must be separated by a line break: curl -i -X PUT -H "Content-Type:text/uri-list" --data-binary @uris.txt http://loc ...

Populating a table with JSON information

Embarking on my Angular journey, I decided to populate a table with data from a JSON file. To my surprise, the table didn't quite match my expectations. Let's dive in. This is the table code: <table class="table table-sm table-bordere ...

Tips for converting text input in a textbox to a Date value

My knowledge of Angular is limited, and we are currently using Angular 10. In our application, there is a textbox where users need to input a date in the format 10202020. This value should then be reformatted as 10/20/2020 and displayed back in the same ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...

Implement ExpressTS on vercel platform

I have recently developed an Express TypeScript project on GitHub and now I am attempting to deploy it to Vercel. The folder structure of the project is as follows, with 'dist' containing app.js and 'src' containing app.ts. dist dto mi ...

Filter is malfunctioning: Issue encountered with reading property 'toLowerCase' as null

I recently developed a filter search application that retrieves data from a MySQL database using a Spring API. Everything was functioning smoothly until I added the filterExpenses() method in the list-expense.component.ts, which resulted in an ERROR. &qu ...

Improving Angular 2 Charts with Multiple Chart Updates

Looking for some help with my code. I am fetching server data using an API for monitoring purposes and have multiple charts set up. The issue is that only the first chart updates every second when I call the API, but the others do not update. Any suggestio ...

Dealing with routing problems within sub-routes using Angular 2 and Express, attempting to serve content from sub-folders

I am currently using Express to serve a local Angular2 application. To enable the Angular2 app to access various node_modules from Express, I have set up the following configuration: config.dependencies = [ { staticPath: './node_modules/@angular/&a ...

Using TypeScript with React: The ideal type for utilizing the useLocation() function from the react-router-dom

I'm facing challenges finding the appropriate type for this specific scenario. Here is a simplified example of redirecting after login. The code snippet below is resulting in a compiler error: Property 'from' does not exist on type &apo ...

The 'input' element does not recognize the property 'formControl', causing a binding issue in Angular Material Autocomplete with Angular 12

Recently, I upgraded my Angular app from version 11 to 12 along with all the dependencies, including Angular Material. However, after running 'ng serve', I encountered the following error: Error: src/app/components/chips/chips.component.html:19:1 ...

Premature updates detected in state cloning process

My program is a simple one designed to showcase an issue I am currently encountering. It involves an array of objects, each containing a sequence number. When a button is clicked, the sequence number of the first object in the array increases by one. To i ...

Is it possible to do inline if else in Angular 2 (v6)?

I am currently working with Angular Material Tables to display a list of columns (displayedColumns). One key requirement I have is to show the "birthday" column in the table using the "date" filter ({{element[column] | date}}), while keeping other columns ...

Tips for utilizing MUI Typography properties in version 5

I'm clear on what needs to be done: obtain the type definition for Typography.variant. However, I'm a bit uncertain on how to actually get these. interface TextProps { variant?: string component?: string onClick?: (event: React.MouseEvent&l ...

How to Handle ISO 8601 Dates in Angular2 Using DatePipe?

I recently attempted to implement a basic date pipe in my angular2 application: Registered: {{user.registered | date:'shortDate'}} However, I encountered the following error: Invalid argument '2016-03-28T07:25:40.824Z' for pipe &apos ...

Is it possible to deduce a generic type from each element in a tuple?

I am currently facing an issue where I need the get function to limit the p parameter to the combination of all the types of key2 in the array. Additionally, key3 should be a keyof TFooKey. type Foo<TFoo, TFooKey extends Record<string, any>> = ...

Exploring the world of Node.js through promises, async/await

I have set up a route in express that involves multiple sql queries and I am unsure of how to organize them using promises and/or async/await. Here is the sequence of operations: Sql query A returns an id necessary for sql query B Sql query B retriev ...

Unable to install vue-property-decorator

When attempting to set up Vue and TypeScript with class style using vue-property-decorator, I encountered a strange script after creating the project. I was anticipating a script like this: <script lang="ts"> import {Component, Vue} from & ...

Show blob file as a PDF document in a popup or dialog box using HTML and TypeScript

I am currently working on integrating TypeScript and HTML to showcase the result of a webservice call as a PDF in a popup/dialog within the same page. While I can successfully open the PDF in a new tab using the window.open(url) method, I'm encounter ...