express.js loop execution timing issue

My current code is not waiting for the loop to finish before printing {"personalchats":[]}

I need to send after the for loop has completed. How can I fix this issue?

connection.query("SELECT * FROM personalchat WHERE user1ID = ? OR user2ID = ?", [userID, userID], function(err, row, fields) {
  if (err)
    console.log(err);

  else {
    personalchats = Array();

    for (var i = 0; i < row.length; i++) {
      if (row[i].user1ID != userID)
        user2ID = row[i].user1ID;
      else
        user2ID = row[i].user2ID;

      connection.query("SELECT * FROM users WHERE userID = ?", [user2ID], function(err2, row2, fields2) {
        if (err)
          console.log(err2);

        else {


          personalchats.push({
            'success': true,
            'userID': row2[0].userID,
            'name': row2[0].name,
            'surname': row2[0].surname,
            'email': row2[0].email
          });
          console.log(personalchats);
        }


      });

    }

    res.send({
      "personalchats": personalchats
    });
  }

});

Answer №1

Here is the suggested code snippet:

connection.query("SELECT * FROM privatechats WHERE user1ID = ? OR user2ID = ?", [userID, userID], function(err, row, fields) {
  if (err)
    console.log(err);

  else {
      privatechats = [];
      var userIDs = [];

      for (var i = 0; i < row.length; i++) {
        if (row[i].user1ID != userID)
          userIDs.push(row[i].user1ID);
        else
          userIDs.push(row[i].user2ID);
      }

      connection.query("SELECT * FROM users WHERE userID in (" + userIDs.join(',') + ")", function(err2, row2, fields2) {
        if (err)
          console.log(err2);

        else {

          row2.forEach(r =>
            privatechats.push({
              'success': true,
              'userID': r.userID,
              'name': r.name,
              'surname': r.surname,
              'email': r.email
            });
          })
          console.log(privatechats);
          res.send({
            "privatechats": privatechats
          });
        }
      });
    }
  }
});

Answer №2

You are facing synchronization issues. The database calls you make require time to finish, and it's possible that you execute the callback before receiving a response when trying to transmit that data. One solution could be utilizing 'Promise.all' or creating a function that runs after each item is added to the array in the callback, checking if all responses have been received before sending the express response.

Answer №3

Your code operates asynchronously. The connection.query function first retrieves results by executing your callback function function(err, row, fields) { }.

Similarly, the second query also returns results by invoking the callback function

function(err2, row2, fields2) { }
. You can access the values within this callback function and log them using console.log(personalchats). Remember to send the result within this callback function as well.

personalchats.push({
    'success': true,
    'userID': row2[0].userID,
    'name': row2[0].name,
    'surname': row2[0].surname,
    'email': row2[0].email
});
console.log(personalchats);
res.send({
    "personalchats": personalchats
});

It is crucial to note that the values of row2 will not be accessible outside the callback function scope.

Ensure you send the result after a successful connection.query operation. Here's a complete example:

connection.query("SELECT * FROM personalchat WHERE user1ID = ? OR user2ID = ?", [userID, userID], function(err, row, fields) {
    if (err)
        console.log(err);
    else {
        personalchats = Array();
        for (var i = 0; i < row.length; i++) {
            if (row[i].user1ID != userID)
                user2ID = row[i].user1ID;
            else
                user2ID = row[i].user2ID;

            connection.query("SELECT * FROM users WHERE userID = ?", [user2ID], function(err2, row2, fields2) {
                if (err)
                    console.log(err2);
                else {
                    personalchats.push({
                        'success': true,
                        'userID': row2[0].userID,
                        'name': row2[0].name,
                        'surname': row2[0].surname,
                        'email': row2[0].email
                    });
                    console.log(personalchats);
                    res.send({
                        "personalchats": personalchats
                    });
                }
            });
        }
    }
});

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

My local requests are being blocked by both Chrome and Firefox

Recently, I've been experimenting with local flash development and trying to inject my swf file into a website served by my test server. To enable loading of local resources in Chrome, I set --disable-web-security. In FireFox, I made the following a ...

NestJS's integration with TypeORM is having trouble connecting to MongoDB

After successfully installing the mongodb software on my Ubuntu server, I obtained the mongo string as follows mongodb://xxx:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec9c8d9f9facd8dec2dedddec2ddd9d5c2dddcd5">[email ...

When using firebase.firestore(), the data displayed is completely different and does not match the content of my actual database documents

I am trying to fetch data from firebase firestore using the following code: let db = firebase.firestore(); let locations = db.collection("location"); console.log("locations", locations); However, the logged data is coming back strange and not showing the ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...

Is it possible to access prop properties within the ready() function?

I am seeing the error message undefined in the console, specifically originating from the ready() function. The issue I am encountering is related to attempting to assign the value of this.users.name to this.userForm.name. Can someone please point out wh ...

Differences Between Vuetify Breakpoints and CSS Helper Classes

As I browse through the Vuetify documentation and various code snippets on the web, I often come across examples that mention using either a Vuetify breakpoint or a CSS helper class to make an element responsive to screen size changes. Is there a preferre ...

Angular JS plugin that locates image links within plain text and transforms them into HTML <img> tags using JavaScript

I am faced with a situation in which I need to show images if the chat messages contain image links, but currently I am only displaying the links as text. One idea I had was to check for the lastIndexOf('.') and extract the file extension to mat ...

Developing a innovative and interactive nested slider using Jssor technology

Trying to implement a dynamic jssor nested slider to showcase albums and images from a mySQL database. Everything works fine with a single album, but when there are two or more albums, the display gets messed up. I'm still learning JavaScript and JQue ...

Step-by-Step Guide: Crafting a Non-Ajax Popup Chat Application

Recently, I created a unique dating website with a one-to-one chat feature similar to Facebook. However, I implemented this using the ajax technique and the setInterval function in JavaScript for regular updates. Upon reflection, I believe that this appr ...

Using Vue.js to increment a value in an array every time a new row is added

In Vue.js, I am attempting to increment an array value when adding a new row. However, I encounter the following error message: You may have an infinite update loop in a component render function. The JavaScript logic looks like this: new Vue({ el: ...

How to choose the placeholder element in Svelte?

I'm currently working on adding a placeholder to a select element, but I'm encountering an issue. When I include the selected attribute for the first option, it displays as an empty space. <select> {#if placeholder} <option v ...

Experiencing difficulty with the communication between C# Controller and HTML/JavaScript View in the MVC framework

Struggling in my MVC web application with passing information between the controller and view. Specifically, I have two text fields in the view that I want to send information from to a method in the controller, then receive the result back in JavaScript t ...

Error in Node-Fetch Mapping: Unable to access property 'map' of an undefined entity

Encountering an issue with the "map" section when attempting to run it - receiving an error message stating "Cannot read property 'map' of undefined" The customers constant is defined above, so I'm unsure where the undefined value is origin ...

Obtaining the most recently inserted ID in Node.js can be achieved by using

Currently in my Nodejs project, I am using the expressjs framework. I am facing an issue where I am trying to retrieve the "last inserted id", but it is showing as "undefined" in the console. How can I successfully get the last inserted id? Below is the ...

Issue encountered with Express.js sendFile leading to ECONNABORTED error

Running a basic node server using Express.js (3.8.6), I am trying to utilize sendFile in order to send a simple HTML file to the client. After checking, the path seems to be correct from the file read. Browser caching has been disabled. The code provided ...

The term "post" is not recognized within the Node.js environment

Utilizing a Google Cloud VM instance to host my node app on Ubuntu 16.04.6. Node.js v11.10.1 and npm v6.7.0 are installed, but encountering a ReferenceError: post is not defined when running the app with node app. Package.json file: {"name": "name", "ve ...

"Implementing a dynamic image thumbnail list with adjustable opacity effects and the ability to add or remove classes

I found a script on another post, but it's not working correctly in my implementation. Everything is functioning properly except that the "selected" class is not being stripped, causing the thumbnails to remain highlighted after being clicked. Here is ...

What is the best way to retrieve a large binary object from Postgres using Node.js and Express?

I have a Node.js REST API script that queries Postgres tables. It works well, but I encounter an issue when trying to fetch large objects using "lo_get" from Postgres - I receive a JavaScript heap out of memory Below is a simple example. index.js const ...

Switching the phone formatting from JavaScript to TypeScript

Below is the JavaScript code that I am attempting to convert to TypeScript: /** * @param {string} value The value to be formatted into a phone number * @returns {string} */ export const formatPhoneString = (value) => { const areaCode = value.substr(0 ...

After implementing the ng-repeat directive, the div element vanishes

I've been working on fetching data from a Json API and displaying it on user event. However, I'm facing an issue where the div disappears whenever I apply the ng-repeat property to it. Despite searching through various tutorials and documentation ...