Is it possible to remove elements from a forEach() loop?

This is the first time I am posting here :)

I have a task at hand which involves looping through keys of an object using a forEach() loop and then pushing specific values into an array for each element. After completing the loop, I need to resolve the array containing all the pushed values.

From what I gather, fetching values outside the context of the forEach() loop can be tricky. Is there a way to achieve this?

Below is a snippet of the code that illustrates what I am trying to accomplish:

    some function returning a promise
    ... 
    ...

    let promisesArray = [];

    //Iterating over each object in the data array
    ObjectJSON.array.forEach((object) => {
      if (object.key === "foo") {
        functionBar()
          .then((response) => {
            promisesArray.push(
              `Object: ${object.key}  |  ${object.someOtherKey}`
            );
          })
          .catch((error) => {
            reject(error);
          });
      }
    });

    resolve(promisesArray);

  }); //end of promise's return

Currently, it is returning an empty array.

The desired output should look something like this instead:

[
  'Object: key1  |  someOtherKey1',
  'Object: key2  |  someOtherKey2',
  'Object: key3  |  someOtherKey3',
  ...
]

Thank you in advance for your insights!

Answer №1

Congratulations on your inaugural post!

While it may be a common question, learning how to implement an asynchronous function in a loop is crucial. You cannot achieve this with .forEach, but you can utilize await within a for loop like so:

let promisesArray = [];

for (let obj of ObjectJSON.array) {
  if (obj.key !== "foo") continue;

  const response = await functionBar();

  promisesArray.push(
    `Object: ${obj.key}  |  ${obj.someOtherKey}`
  );
}

resolve(promisesArray);

To use await, your function will likely need to be declared as async (

async function doSomething() { ...
)

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

What is the ideal approach for setting up the react-native CLI - local module or global installation

I've been following the initial steps to start with React Native from FB's git page at https://facebook.github.io/react-native/docs/getting-started While using nxp or npm installed CLI during the process, I encountered the following error. [!] ...

Update the value of ng-show to false after redirection to the home page from the login page using AngularJS

I am new to angularjs and encountered a problem which required me to change the value of ng-show="false" to ng-show="true" when the user is redirected to the home page after successfully logging in! This is what I am attempting to achieve: .controller(&a ...

Issues with displaying output in C++ arrays

Being relatively new to C++, I acknowledge this question may appear quite basic (or even dumb!). My goal is to return an array of (int i, int j) representing a position or coordinates. Below is the code I've been working on: int* PositionCalculator(i ...

Generate a progress indicator upon user clicking a hyperlink

I am looking to implement a loading bar that appears when the user clicks a link. Additionally, I need to upload data (via Ajax) into div#work if needed, followed by displaying the loading bar. Once the data is successfully uploaded, I want the script to s ...

Is it possible to use regex for matching both spaces and letters exclusively?

I recently created a regular expression that only allows letters. While I'm not very experienced with regex, I am struggling to figure out how to also include spaces in my expression. This is the HTML code I have: <input id="input" /> Below i ...

I'm having trouble identifying the error in my Vue component that uses recursion. How can I pinpoint the

Currently, I am in the process of creating a questionnaire, and the JavaScript file containing the questions is a lengthy 4500 lines. Unfortunately, I am encountering a type error that is proving difficult to pinpoint within the code. Here is a link to the ...

Loading a large quantity of items into state in React Context using Typescript

I am currently working on a React context where I need to bulk load items into the state rather than loading one item at a time using a reducer. The issue lies in the Provider initialization section of the code, specifically in handling the api fetch call ...

An error was thrown at line 474 in module.js

After recently installing nodejs on my laptop, I'm struggling to run a js file in the node environment. I attempted using this command: node C:\Program Files\nodejs\file.js, but encountered the following error: module.js:474 thr ...

Simple steps for integrating JavaScript ads into your WordPress website

Received an advertisement from my client, a 300x250 ad in ad folder consisting of 1 HTML file, 1 JavaScript file, and 1 images folder. Questioning how to integrate these files into the side panel of my Wordpress website's homepage. I've spent a ...

The loader fails to disappear even after the AJAX response has been received

I am currently working on a page that utilizes AJAX to display data. While the data is being fetched, I want to show a loading animation, and once the data has been retrieved, I want the loader to disappear. Below is a snippet of the code where I am attemp ...

Converting Greek text to UTF-8 using Javascript

Currently, I am working on a project with my teacher to digitalize a Greek textbook by transforming it into an online application. This process involves the conversion of a Shapefile, which draws polygons on maps along with polygon descriptions, and mappin ...

Converting canvas illustrations into HTML files

I am in the process of creating a drawing application that will be able to export into HTML/CSS/JavaScript. I plan to use this tutorial as a foundation for the drawing functionality. My goal is to take all the rectangles within the this.shapes = [] array a ...

What is the best way to retrieve a collection of DOM elements in JSX?

I'm in need of rendering certain components only if a specific condition is met. To achieve this, I have written the following inside the render() method: return ( <div className={classes.root}> {registrationScreen && ( * ...

Improve your code by avoiding the use of multiple ngIf statements

Looking for ways to shorten my code for better readability. I have multiple ngIf statements with various conditions for numbering lists (e.g., 1, 1.1, 1.1.1) Here is a snippet of the code from my template: <span *ngIf="...">{{...}}.</span> .. ...

`How can I extract content-disposition headers from an Angular 2 server response?`

I'm having trouble locating the information on how to extract the filename from content disposition in the Angular 2 documentation. Can anyone provide guidance on how to read the headers from the server in Angular 2? Check out this helpful resource on ...

Is it normal for e.target.result to only work after two or three tries?

Attempting to resize an image on the client side before sending it to the server has been challenging for me. Sometimes, the image does not align correctly with the canvas used for resizing. I have noticed that I need to send the resized image at least tw ...

What is the reasoning behind declaring certain variables on the same line as others, while most are declared individually on separate lines?

I've taken on the challenge of learning JS by myself and decided to build a Blackjack game. While following a helpful walkthrough online, I encountered some confusion. On the website, they start by declaring Global variables: var deck; var burnCard; ...

How can the WordPress Gutenberg Popover be positioned to follow the cursor?

I have a component called Popover that I want to position at the cursor's location. For instance, in a component called RichText, if the user's cursor is at the beginning, middle, or end of a sentence, the Popover should appear depending on the c ...

Why is the useContext array appearing empty when accessed in a function within the same context, despite being pre-populated?

I am encountering an issue with my useContext setup, where I provide all logged-in users. When the app runs initially or when users log in, the array is populated with all current users on the server, which works as intended. However, when the "user-connec ...

Is there a way to troubleshoot and improve my Discord bot's kick functionality?

I'm having an issue with my code. When I type in the command "exp kick @user being toxic", it doesn't do anything. It seems to be ignoring my command. Here is the code snippet that I'm using: client.on("message", message => { var comm ...