What is the best approach to retrieve a value from a function that includes a Map.prototype.forEach loop with asynchronous calls?

I have a block of code that looks like this:

async retrieveExportData() {
   const exportStatistics: Object[] = [];
   this.mongoRepositories.forEach( async (repository, key) => {
       await repository.connect();
       let queryResults = await repository.getData();
       exportStatistics.push(...queryResults);
       repository.close();
    });        
  return exportStatistics;
}

this.mongoRepositories is a Map<string, MongoRepo>.

How can I properly return the complete exportStatistics array? The current implementation leaves it empty at the end of the block.

EDIT: This question is distinct from the potential duplicate because of the differences in iterating over a Map compared to iterating over an Array. Updating the question title to reflect this distinction.

Answer №1

After attempting to iterate without using Map.prototype.forEach and encountering compilation errors, I realized that I needed to switch my target environment to es6 from es5 and enable downlevelIteration in my tsconfig.json file. Once I made these changes, the code compiled successfully.

Subsequently, I restructured the code block in the following manner:

async getExportStats() {
  return await this.queryMongo();
}

private async queryMongo() {
   const exportStats: Object[] = [];
   for (const [key, repo] of this.mongoRepos.entries()) {
     await repo.connect();
     const queryResult = await repo.getExportStats();
     exportStats.push(...queryResult);
 }
   return exportStats;
}

Implementing this restructuring resolved the issue that I was facing.

Answer №2

Avoid using await within a for loop. To enhance throughput, utilize Array.prototype.map() along with Promise.all() to simultaneously connect to each repository and fetch data. Then, employ Array.prototype.flat() to merge all the results into a single-dimensional array of objects that is returned from the collection of query results.

async getExportData() {
  const queryResults: Object[][] = await Promise.all(
    Array.from(this.mongoRepositories).map(async ([key, repo]) => {
      await repo.connect();
      const queryResult: Object[] = await repo.getData();
      repo.close();
      return queryResult;
    })
  );
  return queryResults.flat();
}

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

Having trouble retrieving the "history" from props?

I am working with a React component. import * as React from 'react'; import { Component } from 'react'; import { FormControl, Button } from 'react-bootstrap'; type Props = { history: any[]; }; // Question on defining Prop ...

I am encountering compilation errors while trying to run a basic react-dnd list using typescript

I'm currently working on implementing the beautiful-react-dnd example and encountering some errors: import * as React from 'react'; import { DragDropContext, Draggable, Droppable, DroppableProvided, DraggableLocation, DropResult, ...

Utilizing Azure Function Model v4: Establishing a Connection with Express.js

Using Model v4 in my Azure function index.ts import { app } from "@azure/functions"; import azureFunctionHandler from "azure-aws-serverless-express"; import expressApp from "../../app"; app.http("httpTrigger1", { methods: ["GET"], route: "api/{*segme ...

TypeScript failing to recognize dependency for LitElement

Currently, I am encountering an issue with importing two lit elements in my project, namely RootElement and CustomElement. The problem arises when trying to import CustomElement, which unlike RootElement does not show up properly on the UI. My attempt to i ...

Utilizing ngFor to iterate over items within an Observable array serving as unique identifiers

Just starting out with Angular and I'm really impressed with its power so far. I'm using the angularfire2 library to fetch two separate lists from firebase (*.ts): this.list1= this.db.list("list1").valueChanges(); this.list2= this.db.list("list2 ...

Determining When to Activate Button Based on Angular - Verifying That All Choices Have Been Ch

This quiz application requires the user to choose options before proceeding to the next page, with the next button being disabled by default. Once all options are chosen, the next button should become enabled. NOTE: Although the functionality for selecti ...

Node.js is known for automatically adding double quotes to strings. However, is there a way to eliminate them?

After creating a unit test, I noticed that both logics I used led to the same issue. Logic 1: describe('aresFileCopier', () => { test('log error', async () => { await registerDB('ares-test', { client: ' ...

guide to utilizing npm/yarn with tsx react

I've recently made the switch to using TypeScript with React, but I'm encountering a problem. After installing certain packages from npm or yarn, I'm having trouble using them in my .tsx components. The error message suggests looking for @ty ...

Locate the nearest upcoming date and time to today's date in the JSON response

I am currently working with an API that provides a response containing the `start_time` field in JSON format. My goal is to extract the ID from the JSON object whose next date time is closest to the current date and time, excluding any dates from the past. ...

How can I encode and decode a base64 string using AngularJS1 and TypeScript?

I am currently working with Angular1 using TypeScript and I have a question that needs some clarification. Within the environment that I am operating in, is there a method available to encode and decode a string in base64? Despite conducting extensive re ...

When using TypeScript and Material UI, it is important to assign a value to boolean attributes

Trying to implement Material UI code with Typescript for a DisplayCard component, but encountering an error message: (34,23): Value must be set for boolean attributes. The challenge lies in identifying which attribute value is missing... Here is the samp ...

What is the best way to eliminate a particular element from an array produced using the .map() function in

I am experiencing an issue with my EventCell.tsx component. When a user clicks on the component, an event is created by adding an element to the components state. Subsequently, a list of Event.tsx components is rendered using the .map() method. The problem ...

The Angular 13 application encounters a "moment is not a function" error after importing an Angular 13 package

Upgrading a private library named privLib to Angular 13 has been my recent task in order to facilitate the migration of all other projects. However, an issue arises when this library is imported into another project where one of the services utilizes momen ...

Exploring routing within a Higher Order Component in React Native

I am looking to implement a file existence check on every page of my app. The idea is that if a specific file exists, the user should be redirected to another page. One solution I have considered is using a Higher Order Component (HOC) for this purpose. A ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

Tips for retrieving a nested data value within an array

I am currently puzzled by the undefined error I encounter when attempting to access a value using dot notation. The following illustrates my point: My goal is to retrieve the value from within the nested object in the headline color array: ...

Problem with Angular 5: Data Binding Issue未知EncodingException

Struggling to understand... I want to make a GET request to my service to retrieve the specific hardware associated with the barcode I scanned - this part is working correctly. The hardware information is returned as an object that looks like this -> ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

Spotlight a newly generated element produced by the*ngFor directive within Angular 2

In my application, I have a collection of words that are displayed or hidden using *ngFor based on their 'hidden' property. You can view the example on Plunker. The issue arises when the word list becomes extensive, making it challenging to ide ...