1

Here is the code snippet. In the end, I'm getting an empty array. Please note, I'm new to JavaScript.

Pool is a connection to PostgreSQL database using node-postgres package

function execute_query(pool) {
  return new Promise(function(resolve, reject) {
    let column_names = ["column1", "column2", "column3"];
    let array = [];
    for (column_name of column_names) {
      query =
        "SELECT uniqueid FROM table1 ORDER BY " + column_name + " DESC LIMIT 1";

      const sql = {
        text: query,
        rowMode: "array",
      };
      pool.query(sql, (err, result) => {
        if (err) {
          return console.error("Error executing query", err.stack);
        } else {
          if (result.rows.length > 0) {
            array.push(result.rows[0][0]);
          }
        }
      });
    }
    resolve(array);
  });
}

What I actually want is the array with three appended result from the query. As you can see that I'm pushing to array the result.rows[0][0]

I also know that it's an issue of asynchronicity but still, I'm unable to solve it.

Ananth
  • 2,597
  • 1
  • 29
  • 39
Akash Giri
  • 141
  • 1
  • 7
  • `pool.query` here is `async` or `synchronous`? – Guruprasad J Rao Jul 10 '19 at 12:03
  • @GuruprasadRao, async I guess, but you can check it on https://node-postgres.com/features/queries – Akash Giri Jul 10 '19 at 12:08
  • If that's async then I believe you need to wait until all the async operation within for-loop gets completed and since you are having `resolve(array)` without waiting for the query operation, it will always be an empty array.. – Guruprasad J Rao Jul 10 '19 at 12:13
  • @GuruprasadRao, I don't know how to wait and how long to wait for this query to execute completely. As I said, I'm new to JavaScript. :( – Akash Giri Jul 10 '19 at 12:16
  • You probably should also use `console.error("Error executing query", err.stack); reject(err);` (or only `reject(err);` and do the log on the call). Note that it's useless to return `console.error` because console logs always return `undefined`. – Kaddath Jul 10 '19 at 12:18
  • 1
    I've just created a rough fiddle of how it should look like.. **[Here's the link](https://jsfiddle.net/Guruprasad_Rao/L3ydrb2q/3/)**. Just check the code and let me know in case you face any issues. – Guruprasad J Rao Jul 10 '19 at 12:37

0 Answers0