Using Typescript, creating an asynchronous function that utilizes a nested forEach loop to call another asynchronous function

Recently, I encountered an issue with an asynchronous function.

I have two async functions that I am using. The problem arises because the return value is a promise, and I cannot await it inside the foreach loops. I attempted to make both foreach async, but that resulted in inaccurate data being returned.

private getAllProperties = async (props?: IPageDetailsProps) => {
props = props || this.props;
let web = new Web(props.context.pageContext.web.absoluteUrl);
let id = 2;
let pageProps = await web.lists.getByTitle("Site Pages").items.filter(`Id eq '${id}'`).get();
let fieldProps = await web.lists.getByTitle("Site Pages").fields.filter(`Group eq 'Template Columns' or InternalName eq 'Title' or InternalName eq 'Created' or InternalName eq 'Author' or InternalName eq 'Modified' or InternalName eq 'Editor'`).get();
let regionalSettings = await web.regionalSettings.get();
let fieldsList: Array<any> = [];
let obj = JSON.parse(props.fields.toString());

fieldProps.forEach(value => {
  obj.forEach(field => {
    if (field === value.InternalName) {
      let item: any = {};
      item.title = value.Title;
      item.internalName = value.InternalName;
      item.typeAsString = value.TypeAsString;
      if (item.typeAsString === "DateTime") {
        let formatOptions: Intl.DateTimeFormatOptions = {};
        formatOptions.hour12 = !regionalSettings.Time24;
        let date = new Date(pageProps[0][field]);
        item.Data = date.toLocaleString(regionalSettings.LocaleId, formatOptions);
      }
      if (item.typeAsString === "Text" || item.typeAsString === "Note") {
        let text = pageProps[0][field];
        item.Data = text;
      }
      if (item.typeAsString === "User") {
        let personId = field + "Id";
        let user = this.getPersonFromId(pageProps[0][personId])
        item.Data = user;
       // Problem is here, by the fact that the return value from 
       // getPersonFromId is a promise, 
       // since i cant await for it here.
       // I have tried making the both foreach async, but that does not work 
       // as it feeds me bogus data.
       // What i want to do is not do anything until i have an answer
      }
      if (item.typeAsString === "TaxonomyFieldType") {
        item.Data = pageProps[0][field].Label;
      }
      if (item.typeAsString === "TaxonomyFieldTypeMulti") {
        let items = pageProps[0][field];
        let terms = "";
        items.forEach(element => {
          terms += element.Label + "   ";
        });
        item.Data = terms;
      }
      fieldsList.push(item);
    }
  });
});

Function 2

private getPersonFromId = async (id: number) => {
let queryUrl = this.props.context.pageContext.site.absoluteUrl + `/_api/web/getuserbyid(${id})`;
const spSearchConfig: ISPHttpClientConfiguration = {
  defaultODataVersion: ODataVersion.v3
};
let personResponse = await this.props.context.spHttpClient.get(queryUrl, SPHttpClient.configurations.v1.overrideWith(spSearchConfig));
let personResult = await personResponse.json();

let person: any = {};
person.name = personResult.Title;
person.mail = personResult.Email;

return person;

}

Answer №1

When it comes to async functions, using forEach can be tricky because it doesn't have a built-in mechanism to wait for the completion of async callbacks in each iteration. To work around this limitation, you have a few options:

  • Create your own asynchronous version of forEach (it's not too complex; check out a helpful example here)
  • Utilize an existing asynchronous looping library such as async-foreach
  • Stick with the reliable old for...of loop, demonstrated in this Stack Overflow answer: Using async/await with a forEach loop

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

Error in React Typescript: Attempted to access properties of an undefined value

The new Object is displayed in the console but I'm still encountering an error const GetNo = (): string => { console.log(record); if (record.no !== "") return record.no; //<-- Cannot read properties of und ...

Move on to the following iteration within a (Typescript) .forEach loop by using setTimeout

Within my array, I have a list of image URLs that I need to update the src attribute of an img tag every 10 seconds. To achieve this, I am using a forEach loop which includes a setTimeout function that calls a DOM manipulation function (replaceImage) as sh ...

Retrieving the initial data from a fetched JSON file in React

I'm struggling to extract the data from the initial object in a JSON document. const apiUrl = 'https://uniqueapi.com/data.json?limit=1'; function App() { const [items, setItems] = useState([]); useEffect(() => { async functio ...

Struggling to deploy a Typescript React / NestJS application on Heroku due to the error message "error TS2307: Cannot find module"?

Switching from a Typescript React/Express app to using Nest.JS has caused complications when deploying to Heroku. The app runs smoothly locally, but encounters build failures on Heroku. Despite efforts to troubleshoot, it remains unclear whether the issues ...

Is your React conditional rendering malfunctioning due to state issues?

I am attempting to create a component that will only be displayed after clicking on a search button. Below is the current code that I have: Update After making some changes, I am now encountering this error: Error: ERROR in /home/holborn/Documents/Work ...

Incorporate information produced by a Javascript function into PHP

I have developed a website which pulls data from a file (a time value) and initiates a Javascript timer. My goal is to use PHP to continue adding the current time to the loaded time, resulting in an incremental timer that resumes from where it was last l ...

Having trouble locating the error in my Angular and Spring Security application

I am currently working on a project that involves integrating Spring Security with an Angular client. I have encountered an issue where, despite checking for null values in the login form on the Angular side before sending it to the Java application, the J ...

React failing to refresh in browser following compiler error when saved

Recently starting to work with React, I have observed an interesting behavior. When I create my app using create-react-app, it automatically updates when I save it in VSCode, which is normal. However, I have noticed that as soon as I encounter my first c ...

I am attempting to retrieve custom cellRendererParams within the CustomCellRenderer class

I'm currently working with Ag-Grid in my angular application and am trying to implement a custom cell renderer. The tutorial I followed uses ICellRendererParams for the parameter type passed to the init event. agInit(params: ICellRendererParams): void ...

Issue with updating BehaviorSubject not being reflected when called from my service component has been identified

In my HomeComponent, I am currently using *ngIf to switch between 3 components. The focus right now is on the relationship between two of them - the ProductListComponent and the ProductDetailComponent. Inside the ProductListComponent, there is a ProductLis ...

What steps are needed to develop a TypeScript component within Angular framework?

I've been attempting to develop an Angular Component in TypeScript. I'm trying to utilize document.createElement to build a toolbar within my component, but it's not appearing. Below is my Component code: import {Directive, Component, boot ...

Typescript compiler still processing lib files despite setting 'skipLibCheck' to true

Currently, I am working on a project that involves a monorepo with two workspaces (api and frontEnd). Recently, there was an upgrade from Node V10 to V16, and the migration process is almost complete. While I am able to run it locally, I am facing issues w ...

What is the best way to sort through an Array of photo filenames?

https://i.sstatic.net/04cws.pngI have a list of image names that contain UUIDs. images [ "auditid_626_UUID_666666_time__1582577405550.jpg", "auditid_626_UUID_999999_time__1582577405554.jpg", "auditid_626_UUID_999999_time__15825 ...

Testing React Hook Form always returns false for the "isValid" property

When creating a registration modal screen, I encountered an issue with the isValid value when submitting the form. In my local environment (launched by npm start), the isValid value functions correctly without any issues. However, during unit testing us ...

How to refresh a page in Angular Typescript to wait for HTTP calls from the backend

Looking at the code snippet below: The initial HTTP call retrieves multiple IDs of orderlines (items). For each ID, another HTTP call is made to reserve them. Afterward, the page needs to be updated to display the reserved items. When dealing with a larg ...

Framer Motion's "repeatType" property triggering a TypeError

Every time I try to add the repeatType property in my transition, I encounter an error related to the variants prop: index.d.ts(2779, 5): The expected type comes from property 'variants' which is declared here on type 'IntrinsicAttributes ...

Struggling with testing the checkbox when it changes inside the CardHeader Avatar={} component

I've recently implemented a feature similar to the example showcased on MaterialUI's TransferList. However, I'm encountering difficulties accessing a checkbox within the avatar={}. The project utilizes Jest and Enzyme for testing purposes. T ...

Transitioning from click interaction to webpage navigation

I'm feeling really overwhelmed by Typescript. I'm trying to create an event that changes the Google website when a button is clicked. However, when I press the button, the console displays the following error message: [error message on console] D ...

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

Sending nested JSON in Angular 2 Post Request

Are there any efficient ways to handle the task of importing raw JSON data and posting it to a server using an import function? For example, if a user copies and pastes the following JSON: { "name": "testing", "design": [ { "name": "test", ...