Perform asynchronous tasks to assign values to properties of an object within a forEach loop, and then retrieve the object after all asynchronous tasks have been completed

I'm currently working on a code that involves iterating over an array and performing asynchronous tasks for each element in the array. The objective is to execute async operations, retrieve a value from it and assign that value to an object's property before moving on to the next element. Ultimately, I aim to return the final object with all the properties set.

However, I've encountered an issue where my async code is not functioning correctly. The uninitialized variable is being returned prematurely, even before any of the async operations are completed. Additionally, I am unsure if the "await" placed before the forEach loop is having any effect.

generate(): Promise<Properties>{
        return new Promise<Properties>(async resolve => {
            let columns = this._propertyDefinitionRepo.columnNames;
            let properties: Properties;
            await columns.map(async columnName => {
                return new Promise<void>(async resolve => {
                    let distinctValues = await this.doAsyncWork(columnName);
                    properties[this.columnNameToPropertyName(columnName)] = 
                         this.buildPropertyDefinition(columnName, distinctValues);
                    resolve();
                })
            });
            resolve(properties);
        })
    }

Answer №1

Avoid using .map() in this scenario, as it will execute all the callbacks simultaneously rather than waiting for each promise to resolve before proceeding.

Instead, opt for a basic for loop to ensure that the await occurs within the outer function context.

Additionally, steer clear of the promise constructor callback anti-pattern. If you already have a promise available, there's no need to use new Promise.

Therefore, consider revising your code to the following structure:

async generate(): Promise<MonitorProperties>{
    let columns = this._propertyDefinitionRepo.columnNames;
    let properties: Properties;
    for (let columnName of columns) {
        let distinctValues = await this.doAsyncWork(columnName);
        properties[this.columnNameToPropertyName(columnName)] = 
                 this.buildPropertyDefinition(columnName, distinctValues);
    }
    return properties;
}

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

To modify the specified variables in data, I must deconstruct the object

Hello everyone, this is my debut post. I am seeking assistance with destructuring in order to update a variable that is defined within the "data" section. Below are the code snippets I have been working on using Vue. data: () => ({ id: '' ...

Utilizing dynamic data in Vue-chartjs through Pinia stores

I am currently exploring how to integrate a Pinia store data with vue-chartjs in order to create dynamic charts. While referencing this example for guidance, I am facing challenges in making the chart react to changes within the store. Although I can obse ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

What exactly does bivarianceHack aim to achieve within TypeScript type systems?

As I went through the TypeScript types for React, I noticed a unique pattern involving a function declaration called bivarianceHack(): @types/react/index.d.ts type EventHandler<E extends SyntheticEvent<any>> = { bivarianceHack(event: E): void ...

Obtaining the desired element from a function without relying on an event

Recently, I've been working on a sidebar with several links <sidebar-link href="/dashboard" icon="HomeIcon" :is-active="isActive()" /> <sidebar-link href="/test" icon="TestIcon" :is-active=&qu ...

Bootstrap 5 - Zero response for stack traversal

I have recently designed a basic bootstrap 5 template: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, i ...

Stop Code Execution || Lock Screen

Is there a way to address the "challenge" I'm facing? I'm an avid gamer who enjoys customizing my game using JavaScript/jQuery with Greasemonkey/Firefox. There are numerous scripts that alter the DOM and input values. In my custom script, I hav ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

Leverage the power of Laravel and ReactJS to beautifully display images

Currently, I am working on a project where I am incorporating ReactJS into a Laravel blade file. To get started, I included the React CDN and began writing code within the script tag. Everything seems to be going smoothly so far, however, I have encountere ...

javascript code not functioning properly

Something simple! In my asp.net-MVC project, I have a button and an external JavaScript file called mydata.js. This file contains a function called checkJS(). function checkJs() { debugger; alert("your output!!!"); } Here is my code: <div id="m ...

The batch request from localhost for the Google Calendar API has been rejected

When testing the Google Calendar API V3 by submitting a batch request from localhost, I am encountering the error message ""from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is ...

p5.js experiencing issue: Uncaught TypeError - Unable to access property 'transpose3x3' due to null value

I have a simple website built with Flask where I am running several p5.js sketch animations, and everything is working smoothly. However, when I try to add a new sketch that utilizes WEBGL, I encounter the following error: Uncaught TypeError: Cannot read p ...

Converting a JavaScript array into an HTML span: a step-by-step guide

I'm working with an array of objects that looks like this: var data = [{ "name": "Lichtbediening", "category": "category", "info": "Klik voor lichtbediening", "img": "lichtbediening" }, { "name": "Stopcontact", ...

Is it possible to detect the error message "objects cannot be used as a react child" using static analysis?

I recently encountered a bug in my application that was causing it to crash. The issue stemmed from using {object.field} in the JSX, even though {object.field} was an object type and not a valid React child. Since I am working with esLint and Typescript, ...

Looking for assistance with implementing JavaScript to trigger a button click when hovering over a map tooltip

I recently created a map using a WordPress plugin that displays tooltip popups when you click on icons. You can view the map here: My goal is to have the tooltips appear when hovering over each icon, but currently, the tooltips disappear when trying to mo ...

Mysterious sayings encircling the words fetched through ajax

If the localhost is pointing to the folder named www, where the structure looks like: www/ file/test.cpp index.html I want to dynamically load the content of test.cpp into index.html and display it with the help of highlight.js. Below is the cod ...

Learn how to toggle the visibility of a gif image with a button click in an ASP.NET application

I am working on an asp page that includes a button. When the button is clicked, I need to display a gif image. Once the process is complete, the image should be hidden again. Here is the code behind: <head runat="server"> <title>Untitled ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

Combining Firebase Queries with AngularFire2

Update: The issue with encountering empty value fields was due to missing keys in the database, so much of the discussion here may not be relevant to your specific question. If you are seeking a way to merge queries in AngularFire2, the provided answer be ...

What is the best approach to implementing value filtering from a URL in AngularJS?

Unfortunately, I am struggling with filtering the value obtained from the URL. Any ideas on how to fix it? $scope.categoryFilter = function (products){ if ($routeParams.categorySlug == products.category.seo_name){ retu ...