Experiencing difficulty retrieving the variable within a NodeJs function

Currently, I am utilizing the NodeJS postgresql client to retrieve data, iterate through it and provide an output. To accomplish this, I have integrated ExpressJS with the postgresql client.

This is a snippet of my code

    var main_data = an array containing data
    var user_info = {}
    for (var key in result.rows) {
      var user = main_data[key].user

      client.query('SELECT name,age,address FROM users WHERE user_id = $1 LIMIT 1;' , [user], function(queryErr, result){
        var return_data = result.rows[0]
        user_info.name = return_data.name
        user_info.gender = return_data.gender
        user_info.address = return_data.address
        main_data[key].user_info = user_info
     })
    }

    done()
    res.json(main_data)
    return

Unfortunately, upon running the code, the desired output is not obtained. The userinfo does not get added to the main_data as intended but simply displays the main_data variable from the beginning of the code.

This issue cannot be solved by following the recommended duplicate Given that the function lies within a for loop, I cannot execute the response call once the function completes. It is necessary to wait until the entire loop finishes, which could involve over 1000 iterations before making the response call.

Can anyone advise on how to achieve this? What mistakes am I making and how can they be rectified? Thank you in advance

Answer №1

If I were to tackle this task, I'd opt for async.js.

var data = // your result.rows data.

function executeQuery(item, callback){
   // place your query logic here and call the callback with the results
}

async.series(data, executeQuery, function(error){
   // manage any potential errors
}

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 reason behind FieldSelect returning a string instead of an object like FieldCheckbox?

FieldSelect component from Sharetribe documents is giving me a string, while FieldCheckbox is returning a JSON object. In a specific scenario, I want FieldSelect to store a JSON object. How can I achieve this? Below is the code snippet for reference: I& ...

The file updates for Docker Compose are not being properly reflected in my volumes

I have set up my docker-compose file and it runs smoothly. However, when I make changes to a file, the modifications do not reflect in the container. As a newcomer to docker, please forgive me if I am using incorrect terminology. services: front: bui ...

What is the process for displaying user input on the console?

How can I ensure that the server is receiving user input? What steps should I take to print this input to the console? Currently, the console.log statement only displays "About to create new room", but I require the user input as well. Client-Side: // C ...

Obtaining the responseJSON property from a jQuery $.ajax object involves accessing the data returned

Recently, I encountered an issue with my JavaScript code that involves an AJAX request: $ajax = $.ajax({ type: 'GET', url: 'DBConnect.php', data: '', dataType: 'json', success: function(data) {} ...

Storing tasks in the server backend for later access

Struggling to find the most efficient way to store todo list items in the backend. I've heard that storing arrays and objects directly in the backend may not be optimal. Currently working on a web app inspired by Google Keep. Here's some context ...

Query about Javascript/Node/JSON - why isn't this functioning properly?

I thought I had a good grasp on what I was doing until the process started getting jumbled. My code is being executed through Node, not a web browser. For some reason, it jumps to the prompt at the end of the while loop first and I'm not sure why tha ...

Enigmatic void appears above row upon removal of content from a single item

When I click on an item in my grid, the content of that item is moved to a modal. The modal functions properly, but I noticed that when the content is removed from the item, a space appears above it. I have found that using flexbox could solve this issue, ...

Matching the cookie and header in express.js CSURF results in a 403 error code

My express server setup is quite simple: app.use(bodyParser.json()); app.use(cookieParser()); app.use(csurf({ cookie: true })); // routes app.use(Routes imported from another file); Currently, the client side consists of a basic form in react. ...

How to stop an AJAX request using Chrome developer tools?

Is there a way to cancel an initiated ajax request from Chrome Developer Tools? I want to test if my fallback message displays correctly without changing the code. Setting No throttling to Offline will make all calls fail, but I just need one API to fail f ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Guide to accessing HTML elements and saving them in a JSON formatted text using JavaScript

If you have an html form with labels, select boxes, and radio buttons, you can use javascript to store the child elements of that form in a json string format. Here is an example: { "label": { "content": "This is a label" }, "textbox" ...

npm encounters difficulty in initiating the server

I encountered some errors after running npm start in my angular project directory. It was working fine yesterday, but today when I entered the npm start command in my cmd prompt, it started showing errors: This is how my package.json file looks like: { ...

The program encountered an error trying to access the 'version' property of a null value

Just starting my journey with Power BI and looking to customize the visual controls by creating a custom Date slicer using my own Calendar. Followed this tutorial to create a new project, but encountered an error. Although some articles suggested that the ...

The Controller received a JSON object that was empty

I know this question has been asked countless times, but I've tried all solutions with no success. Here's the JSON object in question: { "manufacture":"HP", "model":"testModel", "serialNumber":"testSerial", "description":"Test Descript ...

Customize your Material-UI theme with a unique hover effect for contained buttons

Currently, I am in the process of setting up a theme for Material-Ui on my React application. Within the app, there are two types of buttons that I utilize - contained and outlined. The issue lies with the hover effect on the contained button (while the ou ...

An issue with a dependency occurred / A syntax error was found in bower.json

After setting up a new ASP.NET V5 web project, I included a NPM configuration file named package.json: { "version": "1.0.0", "name": "ASP.NET", "private": true, "devDependencies": ...

After running `npm uninstall -g angular-cli`, I thought I had successfully removed angular-cli from my system. To my surprise, when I checked `ng --

What's the deal here? I uninstalled angular-cli globally on my laptop by running npm uninstall -g angular-cli, and now it's gone. But on my desktop, I can still use ng --version even after removing angular-cli globally. Any idea what's ha ...

Placing a dropdown menu on top of an image

I currently have a slightly rotated menu bar with two buttons as an example: https://i.stack.imgur.com/0sI2P.jpg Due to the rotation, normal HTML handling is not feasible. I am considering using a <map> element to create hyperlinks over the menu it ...

Aggregating MongoDB with project and unwinding an empty array

After encountering a similar problem to the one described by the author in this question, I found a solution provided by another user on Stack Overflow: Unwind empty array in mongodb However, after updating my MongoDB/Mongoose recently, I am now facing a ...

Tips for aligning placeholder and text at the center in a React Material UI TextField

Existing Layout: https://i.stack.imgur.com/Zv4Tg.png Desired Layout: https://i.stack.imgur.com/Xuj6O.png The TextField element is displayed as follows: <TextField multiline={false} autoFocus placeholder={props.defaultAmt} ...