Async problems arise when using nested forEach loops, causing them to complete at varying speeds

Using express, neat-csv, and mongoose has led me to a scenario where I need to verify the existence of a series of users when a batch register call is made from a .csv file. The current process works smoothly as long as all information is input correctly, but it only catches errors inconsistently. To test this, I intentionally uploaded a .csv file that does not meet the requirements (some users already exist), resulting in most executions running fine and returning the list of existing users.

However, there are instances where it randomly returns the completed array of users anyway. Upon inspecting my code, I noticed that the issue lies in the following section:

//data consists of the data fetched from neat-csv, allUsers represents an array of user IDs, and I check the database for existing users before proceeding further

  let Failed = false;          

  allUsers.forEach(async (id, index) => {
    await User.findById(id)
      .then(async users => {
        console.log('User', users);
        console.log('indexes', index, allPartners.length - 1)
        if (users === null && index !== allUsers.length - 1) return Failed = true;
        else if (users && Failed === false && index === allUsers.length - 1) {
          console.log('submitted indexes', index, allPartners.length - 1)
          data.forEach((user, i) => {
            console.log('Failed', Failed);
            if (i !== data.length - 1) user.addValue = 'newValue';
            else res.json(data).status(200);
          })
        } else if (index === allUsers.length - 1) {
          // process a failed search
        } else return Failed = true;
      })
      .catch(err => res.json({message: 'Failed to send a compatible .csv file.'}).status(401));
    });

The issue is specifically with

else if (users && Failed === false && index === allUsers.length - 1) {
. If it mistakenly believes that it has reached the end without any errors, it will execute erroneously.

[0] User {object}
[0] Failed false
[0] indexes 2 2
[0] submitted indexes 2 2
[0] User null
[0] Failed false
[0] indexes 0 2
[0] User null
[0] Failed true
[0] indexes 1 2

The root cause seems to be related to the asynchronous nature of JavaScript when dealing with nested loops. I attempted to incorporate some async/await methods, but they did not produce the desired outcome. Is there a way to ensure that JavaScript waits for the first loop to finish before proceeding? This would avoid the need for such deeply nested loops. Alternatively, is there a method to guarantee synchronous execution of the loops?

I am open to suggestions using ES6+ or Bluebird, but any advice would be valuable at this point.

Answer №1

Disclaimer: The information provided here is intended to give you a general direction, rather than an exact solution.

To improve efficiency in your query, consider utilizing Mongo's ability to search the entire array automatically.

Look into the $in operator for more details.

The following pseudo-code assumes that the Mongo query is structured according to the documentation for .find(), and that "User" is a MongoDB collection.

const allUsers = getIdsFromCSV(filename);

async function checkForExistingUsers() {
    const users = await User.find({ id: { $in: allUsers } }).toArray();

    return users.length > 0;
};

const exist = checkForExistingUsers();

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

"Successful deletion with Express, yet error message of 'Not Found' displayed

I've implemented this boilerplate to build my API, utilizing express and typeorm with typescript. When attempting to delete a question, the deletion process works smoothly but I receive a 404 not found response. Below is my Question.ts class: @Entit ...

What could be causing the lack of updates in my shared service across all components?

I have implemented an Angular2 app where I am initializing an authentication service called LocalStorage which I want to be accessible across all my components: bootstrap(AppComponent, [ ROUTER_PROVIDERS, LocalStorage ]); The definition of the Lo ...

The method of reading a unique array of objects for each radio button

Currently, I am facing an issue when trying to retrieve unique elements for each radio button from the database. The data structure and information obtained from the database are as follows: { FormularID: 182, CampaignID: 14, FormLabel: & ...

Exploring the Power of Multiple FindOne Queries in MongoDB

I have been working on expanding the data fields returned by our API. Currently, the API retrieves student information using the find method, and also includes some project details by retrieving the student info and using findOne to obtain information abou ...

What is the object pattern in Typescript?

Recently delving into TypeScript, I am eager to learn how to define an interface for the following type of object: const branch = { 'CN': { 'name': 'CN Name', 'branch': 'Chinoise', 'url& ...

Retrieve the request URL within the server.js file using Node.js

I am working on my server.js file where I define the server and all its settings. In order to properly set up my server, I need to determine the request URL before declaring those settings. This is important because the settings depend on the specific req ...

Clicking on the modal button causes the code to run multiple times in JQuery and JavaScript

Hello, I'm experiencing an issue where the code inside a modal is being executed multiple times when the modal button is clicked. For example, if I click the modal button once, the code runs once; if I click it twice, the code runs twice, and so on. ...

The automatic CSS cookie bar functions smoothly, but could benefit from a small delay

I successfully added a pure CSS cookie bar to my website, but there is a slight issue. When entering the site, the cookie bar is the first thing that appears, and then it goes up and down before settling at the end. How can I make my cookie bar only go do ...

When the HTML content matches a specific value, initiate a click event to trigger

Can anyone help me troubleshoot? I've tried multiple methods but can't seem to get it right. Here's a breakdown of what I'm attempting to accomplish: #info-NUMBER-btn shows Click to display more information. #info-NUMBER CSS is set t ...

I would like to share tips on integrating React.js with a backend through React Hooks and the process of deploying the application on Heroku

Looking to integrate the React front-end framework with my backend express.js and EJS using React Hooks. I am familiar with using app.get() in Express for handling server requests, but unsure how to coordinate that with starting a React server on localh ...

Having trouble retrieving data from the MongoDB database using Node.js

Having trouble with data retrieval from MongoDb Successfully connected to MongoDb, but when using the find command, it should return an empty collection, yet nothing is being returned. What could be causing this issue and how can it be monitored through ...

What steps do I need to follow to integrate Polymer CLI v-2.0 with Node.js and Express to develop an application?

After setting up an Express server and installing polymer-cli, I am trying to figure out how to run Polymer code using Express. Any guidance on this? ...

Customize checkbox and label using jQuery

I have a scenario where I have multiple checkboxes and corresponding labels. When the answer is correct, I want to change the background color of the selected checkbox and label. <input type="checkbox" id="a" class="check-with-label" /> <label fo ...

Having trouble getting my JS/CSS code to work for a single image music play/pause button. Any suggestions on how to fix it?

I'm currently working on a project and trying to incorporate a music button into the navigation bar. The goal is for the song to play when clicked, and then pause when clicked again. However, I've encountered some issues with getting it to functi ...

Utilizing Express-sessions to generate a fresh session with each new request

I'm facing an issue with my express backend using express-sessions and Angular frontend. Every time the frontend makes a request, a new session is created by express-sessions. I suspect the problem lies in Angular not sending the cookie back, as I don ...

Is there a way to add additional text to a text element within an SVG?

Is it possible to append a new text element at the end of the data label by clicking on that particular text? I have attempted to implement this in my code but the additional text is not being displayed as expected: circleGroup.selectAll("text") ...

"Encountering problem with sending data to server through Ajax

I am facing a very complex issue that requires an in-depth understanding. If this interests you, please continue reading. I have developed a program from scratch that generates an HTML page for user data input and submission. The submitted data is sent to ...

What could be causing this error to appear when using Next.js middleware?

The Issue at Hand Currently, I am in the process of setting up an authentication system using Next.js, Prisma, and NextAuth's Email Provider strategy. My goal is to implement Next.js middleware to redirect any requests that do not have a valid sessio ...

Looping through alert items

Below is the code snippet I am working with: <tr ng-repeat="sce in users"> <td> <a href="/test/delete?id={{sce.id}}" onclick="return confirm('You really want to delete'+ {{sce.name}} + 'from list');" > ...

Utilizing JavaScript Fetch with User Input to Integrate OpenWeather API Retains Previous Data on HTML Page

I have been working with JavaScript Fetch to retrieve data from the OpenWeather API. In my project, I have created a form where users can input the name of a city to view its weather information. However, I am facing an issue where the data from the previo ...