What is the best way to ensure a function returning a promise works effectively within a forEach loop?

Are you facing challenges using a function that returns a promise inside a forEach loop due to the asynchronous nature of the function? It seems like the forEach loop completes before the promise can finish fetching or manipulating the data.

Below is a code snippet highlighting this issue:

        var todaysTopItemsBySaleFrequency = [];

        listOfItemIdsAndSaleFrequency.forEach((item) => {

            Product.findById(item.itemId).then((foundItem) => {

                var fullItemData = foundItem.toJSON();

                fullItemData.occurrences = item.occurrences;

                todaysTopItemsBySaleFrequency.push(fullItemData);

            });

        });

        return res.status(200).json(todaysTopItemsBySaleFrequency);

The array todaysTopItemsBySaleFrequency is returned to the client empty because the findById function from mongoose returns a promise and does not fully populate the array before sending the response back to the client.

Answer №1

To handle functions that return something or a promise for it, the use of a map loop is necessary instead of a forEach loop. In this case, Promise.all can be used on the resulting array of promises:

Promise.all(listOfItemIdsAndSaleFrequency.map(item => 
    Product.findById(item.itemId).then(foundItem => {
       var fullItemData = foundItem.toJSON();
       fullItemData.occurrences = item.occurrences;
       return fullItemData;
    })
)).then(todaysTopItemsBySaleFrequency => {
    res.status(200).json(todaysTopItemsBySaleFrequency);
})

Answer №2

This code snippet demonstrates how to utilize AngularJS to create a promise array within a foreach loop. By leveraging the $q service, you can efficiently manage asynchronous requests.

                    var promiseArray = [];
                    for (var j = 0; j < someData.length; j++) {

                        var apiRequest = $http({
                            method: 'GET',
                            url: apiUrl,
                        });
                        promiseArray.push(apiRequest);
                    }
                    $q.all(promiseArray).then(function (result) {
                        //executed when all promises are resolved
                    }, function (error) {

                        console.log(error);
                    });

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

Achieve a new line break when the user hits the "Enter" key using HTML and JavaScript

I'm in the process of developing a Chrome Extension that allows users to create a to-do list. My goal is to enable users to submit their task by pressing the "Enter" key, which should move the task to the next line after submission. I am currently fac ...

The issue persists with the addEventListener function not working multiple times

My issue is that the addEventListener function is only working for the 'scroll' event and not for 'addMoreFields' or 'removeFields'. If I move the scroll section down, then it works for 'addMoreFields' and 'remo ...

When retrieving keys and values from an associative array in PHP, it will not return all keys and values if they have the same key name

Currently, I am analyzing a file with the following data: Vélez Sarsfield|Zárate, Mauro|8|0|0|1|9 Estudiantes|Carrillo, Guido|5|1|0|2|8 Boca Juniors|Gigliotti, Emanuel|3|2|0|2|7 River Plate|Carbonero, Carlos Mario|4|2|0|0|6 Arsenal|Echeverría, Mariano|6 ...

Emberjs Troubleshooting: Issue with Sending Many-To-Many JSON Parameters

My current versions are ember-cli 1.13.8 and ember-data 1.13.11, using ActiveModelAdapter. I am working with two objects: posts and users. On an individual post page, I have implemented an action that allows users to watch/follow the post. //post model j ...

Retrieve the values by accessing an element upon clicking the "Submit" button

Here is an interesting example that I found on this website I am currently working on a simple webpage to display both the current forecast and extended forecast. This is my Index.html: <!DOCTYPE html> <!-- To change this license header, choose ...

The error message "ReferenceError: obj is not defined using webcomponents & polymer" indicates that the object

I am diving into the world of web components for the first time with this project, and my knowledge of js/jquery is quite limited. I'm encountering an issue and I'm unsure why it's happening. I've created a custom element in "search-fo ...

What is the method to create a polygon in its entirety by utilizing a for loop within Javascript?

After successfully using the Canvas of HTML to draw a convex polygon, I encountered an issue. In the provided code snippet, t2 represents an array of points with getX() and getY() methods. The drawing function performs as expected until it reaches the seg ...

Multiple CSS styles are being employed simultaneously to render the webpage

Currently, I am utilizing JavaScript to choose different CSS styles for various accessibility options such as black on white text and larger text. The issue I am facing arises when switching the CSS sheet, as elements from previously selected sheets are st ...

When calling undefined typescript, the async function does not return a value but displays its result afterwards

When I debug my function, it waits until the return statement, but when I call the function, it returns undefined and the errors are also undefined. I'm not sure why this is happening. import userModel from '../Models/user.model'; const bcr ...

Tips for successfully passing multiple data IDs in a Bootstrap modal

Greetings! I am currently facing a challenge with passing multiple data IDs into a bootstrap modal. When I manually assign the data IDs, everything works perfectly: <a id="testB" href="#my_modal2" data-toggle="modal" data-book-id='{"id":10,"name ...

The issue of JQuery and document ready being triggered multiple times while loading data into a control

Ever since implementing the load function to load content into a DIV upon document ready, I've noticed that all associated functions are firing multiple times (often twice, and sometimes endlessly). The scripts included in the head tag of all pages a ...

Can someone please explain how to include a custom icon on Select component in Mantine without using an image from Tabler Icons library?

Hey there, I'm new to using Mantine and I'm currently working on a Search Component. Instead of utilizing an image from the tabler icons like in the Mantine examples, my goal is to include a picture from my own assets. Here's what I've ...

Scroll down 1 page using Javascript and Jquery

Hey there! I'm looking to create a website where a small scroll on the mouse wheel will take the site to the next anchor. It's kind of hard to explain, but one good example is the Tesla Model 3 website on the US site here. Does anyone have any t ...

What is the process of displaying an image every 5 seconds in React?

Each time you visit this URL: , a new image is displayed. I am trying to make my React component show a different image with this URL every 5 seconds, but I'm having trouble. Here is the code I have: import { useEffect, useState } from "react"; ...

Get the desired text following the second <br> tag using jQuery

I am trying to identify a specific string that comes after the second occurrence of <br> tag and then check if this string contains any numbers. If there are no numbers present, I want an alert to be shown. The code for performing this action is func ...

Is it feasible to bypass the dialog box on beforeunload?

Currently, I am utilizing jQuery's bind method like so: $(window).bind('beforeunload', function() { //my code return ""; } In Mozilla Firefox and IE8, everything works smoothly without including the "return "";" statement. No pesk ...

Leveraging Material-UI in Electron Environment

I'm currently working on an electron app using React and incorporating Material-UI for the user interface. I've added a datepicker and timepicker to a component, but when clicking on the input in the electron app, nothing happens. I'm unsure ...

The border of the Material UI Toggle Button is not appearing

There seems to be an issue with the left border not appearing in the toggle bar below that I created using MuiToggleButton. Any idea what could be causing this? Thank you in advance. view image here view image here Just a note: it works correctly in the ...

Generating numerous div elements with jQuery's zIndex property

While attempting to create a function that runs on the $(document).ready() event and is supposed to generate a new div, I encountered an issue. Whenever I try to create another div with the same DOM and Class attributes but in a different position, a probl ...

Struggling with implementing nested for loops

I am struggling to find a solution for this issue. I need to compare the content of two arrays with each other. If they are exactly the same, I want to execute the if statement; otherwise, I want the else statement to be executed. The current setup is ca ...