This is my code:

  const queryFirstNames = function (qString) {
    let firstNameMatches;
    client.query('SELECT * FROM famous_people WHERE first_name = $1', [qString], (err, result) => {
      if (err) {
        return console.error('error running query', err);
      }

      firstNameMatches = result.rows;
      return firstNameMatches;
      client.end();
   });
 };

 console.log(queryFirstNames(qString));
});

This code return undefined and doesn't end the connection with the database

But if I console.log firstNameMatches inside the function instead of returning and then just invoke the function without console logging, I get the result I want, and the database connection closes properly.

What I want to do is return the result of this query and use it in another function, so I don't want it to console log the result, but when I try to return the result, it gives me undefined, and doesn't close the database connection either.

2

There are 2 answers

2
Chris E On BEST ANSWER

I believe that the issue you are having is that when you are returning firstNameMatches, you are returning it just to the callback for client.query. firstNameMatches is set inside of the context of the queryFirstNames function, however you never return that back. That being said, you are also utilizing an async call to client.query. This means that when you return from the queryFirstNames function, chances are you haven't finished querying. Per this, I am pretty sure you want to utilize promises to manage this or the events like one of the other answers.

In addition to this, you are going to want to move your return to before the client.end. To play with my answer, I created a jsfiddle that you can see here. I had to create my own promise via Promise just to mock out the client executing the query.

  const queryFirstNames = function (qString) {
    let firstNameMatches;
    client.query('SELECT * FROM famous_people WHERE first_name = $1', [qString])
    .then((result) => {

      firstNameMatches = result.rows;
      client.end();
      return firstNameMatches;
    })
    .then(f => {
        console.log(f);
    })
    .catch(e => {
      if (err) {
        return console.error('error running query', err);
      }
    });
  };
1
cp1 On

You are returning the call before you even execute client.end(); This way your client connection will never end. You can do something like this:

const query = client.query(
    'SELECT * FROM famous_people WHERE first_name = $1',
    [qString], 
    (err, result) => {
        if (err) {
            return console.error('error running query', err);
        }
    });

    query.on('row', (row) => {
      results.push(row);
    });

   // After all data is returned, close connection and return results
    query.on('end', () => {
        return res.json(results);
    });