0

I'm extracting some data from the database, to use it in my nodejs app. I'm using node-postgres to connect to the db (https://node-postgres.com/).

I went through the guidance multiple times and tried querying it in different ways (callback, promise, using pool and client), but always get errors.

const { Pool } = require('pg');

const pool = new Pool({
  user: 'user',
  host: 'host',
  database: 'db',
  password: 'pass',
  port: port,
});

pool.query('SELECT * from table').then(res=> {
var projects = res.rows; 
console.log(projects); 
return projects;
});

//... few other operations on projects data to follow before exports

exports.raw = projects;

I can see the data in the console output, so the connection is working, but when I try to run the code I get

ReferenceError: projects is not defined.

Grateful for any help with this.

Anna
  • 3
  • 2
  • Yes... That's how asynchronism works :) Not everything is available all the time. Besides, your `projects` variable is defined only within the callback. – Jeremy Thille Aug 21 '19 at 14:45
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jeremy Thille Aug 21 '19 at 14:45
  • You are defining `projects` inside the arrow function passed to `then`. It is not reachable from the outside because of the **scope** – Andrea Simone Costa Aug 21 '19 at 14:47
  • I think https://stackoverflow.com/questions/51142495/node-js-async-await-module-export could be a solution for you if you need to export something async – Andrea Simone Costa Aug 21 '19 at 14:50

3 Answers3

0

You can simply achieve by async/await code format

users.js

const users = {};

const { Pool } = require('pg');

const pool = new Pool({
  user: 'user',
  host: 'host',
  database: 'db',
  password: 'pass',
  port: process.env.port,
});

users.getUsers = async () => {
  try {
    const result = await pool.query('SELECT * FROM users');
    console.log(result);
    return result;
  } catch (err) {
    console.error(err);
    throw err;
  }
};

module.exports = users;

friends.js

const friends = {};

const users = require('./users');

friends.getSampleData = async () => {
  try {
    const result = await users.getUsers();
    console.log(result);
    return result;
  } catch (err) {
    console.error(err);
    throw err;
  }
};

module.exports = friends;

Note async/await only works on a function which returns a Promise.

Neel Rathod
  • 2,013
  • 12
  • 28
0

Just like Jeremy answered, create a getter method in order to fetch data, don't try to store it before you need it.

const fetchData = async() => {
  const res = await pool.query('SELECT * from table')
  return res.rows;
}

const myDesiredData = fetchData()
MilosMarkoni
  • 171
  • 8
-1

Try the async/await syntax :

let projects;

(async () => {
    const res = await pool.query('SELECT * from table');
    projects = res.rows;
})();

exports.raw = projects;
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • `async` also returns a promise. it makes no different than using .then as in OPs snippet. – AZ_ Aug 21 '19 at 14:52
  • I don't return anything from my async function. It's not the point. I define `projects`. – Jeremy Thille Aug 21 '19 at 14:53
  • that's the point. you will have to return the promise upto the end. that's how the event loop works, your module.exports will not wait for the self invoking function to complete. also why a self invoking function? It will be executed at the very same time you will import the module. why you will want to fetch the complete data even when not required. – AZ_ Aug 21 '19 at 14:58
  • uh, well, I don't see why I should return a Promise. Return to what? As long as `projects` is defined? Also, are you sure that `module.exports` won't wait for the `async` function? Why would it not, since we `await` the call? – Jeremy Thille Aug 21 '19 at 15:02
  • return to the next method upto the client.yes I am sure `module.exports` wont wait. `await` is powerful online inside the `async` not outside. check the fiddle https://jsfiddle.net/fsed9zco/ – AZ_ Aug 21 '19 at 15:13
  • Link not found (?) but fair enough, thanks for the explanation :) – Jeremy Thille Aug 21 '19 at 15:14