Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution.

Here is my code:

var array =[];
       for(var i = 0 ; i< latitude.length; i++){       
    client.query("SELECT value->>'xxxx' as xxxx_details FROM yyyyy WHERE ST_DWithin(ST_GeogFromText('SRID=4326;POINT ("+latitude[i]+" "+longitude[i]+")'), geography(the_geom), " + radius + ")", function(err, row, fields) {               
                       array.push(row.rows[0]);
       }   
                console.log("bbbbbbbbb=" +array);

What I am trying to achieve is to have the array printed after all the queries have been executed inside the for loop. Currently, it is being printed before the array is fully populated. Can someone help me solve this issue? Thank you in advance.

Answer №1

The issue lies in the nature of client.query being asynchronous, with results only accessible within the callback function.

One potential solution is utilizing async.js. For more insights, refer to this informative article.

As highlighted in the referenced article, you can iterate through a collection and execute code for each item. In your scenario, consider creating an array of indexes or using a foreach loop to generate an array of SQL query statements, subsequently executing operations for each query.

If 'queries' represents an array of query strings, then a possible implementation could look like:

async.forEach(queries, function(query, callback) {
    client.query(query, function(err, row, fields){
        array.push(row.rows[0]);
        callback(); // indicating completion of this task to async
    });
}, function(err) {
    if (err) return next(err);

    // all queries have been executed
});

It's worth noting that there are also forEachLimit method for parallel processing and forEachSeries for sequential execution.

UPDATE:

An improved approach involves leveraging async/await functionality, which is now accessible when using TypeScript compiled to ES6+ and working with node 4+ (which supports generators).

I delve into the specifics in my comprehensive repository on Node.js practices.

A snippet from the repo demonstrates awaiting an async call within a loop, ensuring asynchronous nature while pausing execution until completion. Additionally, it streamlines error handling through try/catch blocks.

// Leveraging await simplifies linear coding.
// Facilitates calling async functions within loops.
// Provides straightforward error management via try/catch.
var quotes: IQuote[];
var tries: number = 0;
while (true) {
    try {
        ++tries;
        // ASYNC/AWAIT
        quotes = await this._store.find<IQuote>({});
        break;
    }
    catch (err) {
        if (tries == 3) { throw err; }
    }
}

return quotes;

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 JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...

react-leaflet LayerSelection creates redundant entries in table

Here is the React version I am using: 16.0.0 And for react-leaflet: 1.6.6 I recently attempted to implement a layer controller on my map which consists of two layers, each containing multiple markers. Below is an example of what I have been working on. i ...

"Issue with Material-ui Autocomplete where the defaultValue does not function properly

The defaultValue was set to "Chairs" but it doesn't seem to be working as expected. Here is the code snippet: import React, { useState } from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomple ...

Immersive Visual Symphony through Dynamic Multi-Layered

My goal is to create captivating animations for my multiple background images. Here's the CSS code I've come up with: .header { background-image: url('/img/cloud2.png'), url('/img/cloud3.png'), url('/img/cloud1.png&apos ...

Having trouble downloading files in React and Node.js

I need to retrieve a specific file from the uploads folder and download it into my download folder. Both folders are located in the same directory, and the file's name is BasicUserFile-id.jpg. On my second attempt, I tried hardcoding the file name bu ...

The React component continuously refreshes whenever the screen is resized or a different tab is opened

I've encountered a bizarre issue on my portfolio site where a diagonal circle is generated every few seconds. The problem arises when I minimize the window or switch tabs, and upon returning, multiple circles populate the screen simultaneously. This b ...

What causes scope to be undefined in Angular?

Using ionic to develop a hybrid app has been a smooth experience, especially with android! This is my login HTML: <body ng-app="starter"> <head> <script src="phonegap.js"></script> </head> <ion-header-ba ...

ESLint has detected an unexpected use of an underscore in the variable name "__place". Avoid using dangling underscores in variable names to follow best coding practices

I received the JSON response shown below. To validate the _place, I used responseData.search[0].edges[0].node._place { "data": { "search": [ { "_place": "SearchResultItemConnection", "edges": [ { "cursor": ...

The checkbox is displayed as selected after being clicked in conjunction with another checkbox

In the tree structure, there are checkboxes that behave strangely when clicked. I have already read a similar discussion here. The problem I am encountering is that when I click on an item, it gets checked but the console does not show it as checked immed ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...

Enhancing Angular input validators with updates

Working on a project with Angular 6, I have set up an input field using mat-input from the Angular Material framework and assigned it an id for FormGroup validation. However, when I initialize my TypeScript class and update the input value, the validator d ...

Google Extension PHP Plugin

Is it feasible to integrate a PHP file into a Google Extension for Chrome? I've been exploring the idea of creating an extension and most resources only mention HTML, CSS, and JavaScript. Any guidance on using PHP in the extension would be highly valu ...

Detecting the Escape key when the browser's search bar is open - a step-by-step guide

One feature on my website is an editor window that can be closed using the Escape key. The functionality is implemented in JavaScript: $(document).keyup( function(e) { // Closing editor window with ESCAPE KEY if(e.which == 27) { // Clic ...

Can the Node DNS module be incorporated into Angular code?

I am facing a requirement where I must perform a DNS lookup from client-side code built in Angular. Is it feasible to utilize the DNS module from https://nodejs.org/api/dns.html in Angular? ...

how can I increase directory scores in node js

This is how my node app's structure looks like. https://i.stack.imgur.com/a68Ii.png I'm attempting to import the auth.js file into the user.js file. The following import statement is working fine: const auth = require('./../controllers/a ...

When attempting to execute the 'npm start' command, an error was encountered stating "start" script is

Encountering an issue when running "npm start." Other users have addressed similar problems by adjusting the package.json file, so I made modifications on mine: "scripts": { "start": "node app.js" }, However, t ...

After a period of 10 minutes with no activity, proceed to the next page

I am in the process of developing a custom local website that will be displayed on a large touch screen at my current workplace. Only one user can interact with it at a time. My client has requested a screensaver feature to appear after 10 minutes of no i ...

Tips for toggling the display of multiple ion-input fields based on the selected value from an ion-select dropdown

I am working with an ion-select element that contains options from 1 to 10. <ion-label> Select how many input fields</ion-label> <ion-select> <ion-option value="0"> Zero</ion-option> <ion-option value="1"> One</ion- ...

Using Angular's ng-repeat to iterate through an array and display its objects within another array

One of my tasks involves retrieving json objects through a simple post method. The json contains multiple campaigns, organized in an array structure. Each campaign holds slots, which are also arrays with one or more base_image elements. My goal is to di ...

The Dropdown Button Functions Once and Then Stops

I am facing a challenge in implementing a button within an HTML table that triggers a dropdown menu when clicked, and closes upon another click or when the user clicks outside the menu. Oddly, the button only seems to work once before completely losing fun ...