0
app.get('/some_endpoint', function (req, res) {

    function getData() {
        pool.query('SELECT * FROM users WHERE id = $1', [40], (error, res) => {
            if (error) {
                throw error
            }
            console.log(res.rows[0]); // this logs the correct output
            return res.rows[0];
        });
    }

    let data = getData(); 
    console.log(data);      // this logs undefined
});

I can't get data from the query, for some reason it is undefined sometimes, and sometimes it is not ---0\_/0\_/0---

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Xavi Font
  • 296
  • 4
  • 19
  • 2
    This will answer your question: [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Bergi Apr 26 '22 at 04:28
  • @Bergi no, I don't care if it is async or not, thanks anyway – Xavi Font Apr 26 '22 at 04:30
  • 1
    Well you should, because it *is* asynchronous. And `data` isn't "*sometimes*" `undefined`, it *always* is. – Bergi Apr 26 '22 at 04:33
  • 1
    Your `return res.rows[0]` is returning from the `pool.query()` callback, NOT from the `getData()` function. In fact, because `pool.query()` is non-blocking and asynchronous, the `getData()` function returns BEFORE the `pool.query()` callback is even called. It is impossible to return that value from `getData()`. Instead, read the duplicate referenced by Bergi and see what your options are (hint: they are using a promise, callback or event or similar mechanism). Or just put `res.send()` inside the `pool.query()` callback and just handle the data there and stop trying to return it. – jfriend00 Apr 26 '22 at 04:50

0 Answers0