简体   繁体   中英

How to return PostgreSQL database result by using PG and Node only?

I am trying to give myself a practice to just use pure node as my server and PG to connect to PostgreSQL. What I want to do here is to return the result after querying from database and know it is problem of async. So how could I return the value from the callback function inside client.query.

function showAllMovies(){


pg.connect(connectionString, function (err, client, done) {
    if (err) {
      console.log('Can not log into database');
    } else {
      console.log('Connect to database...');
      client.query('SELECT * FROM movies', function (err, result) {
        done();  // client idles for 30 seconds before closing
        var result = JSON.stringify(result.rows[0].movie);
        console.log(result);
        return result;
      });
    }
  });
  pg.end();
}

You can't return the value directly. You need to add a callback of your own to your function, which you will need to call, and provide the result to that callback.

For instance:

function showAllMovies(callback)
{
  pg.connect(connectionString, function (err, client, done)
  {
    if (err)
    {
      console.log('Can not log into database');
    }
    else
    {
      console.log('Connect to database...');
      client.query('SELECT * FROM movies', function (err, result)
      {
        callback(result.rows[0].movie);
        done();
      });
    }
  });
}

In this case, you can use it in your response handler like this:

showAllMovies(function(movie) { response.write('<li>'+movie+'</li>'); });

Note that this is just an example, you should actually do HTML escaping before output.

Alternatively, if you're responding to a request and using Express, you can simply pass down the response object and call one of its methods. For instance:

app.get('/movies', function(req,res)
{
  pg.connect(connectionString, function (err, client, done)
  {
    if (err)
    {
      console.log('Can not log into database');
    }
    else
    {
      console.log('Connect to database...');
      client.query('SELECT * FROM movies', function (err, result)
      {
        res.write('<li>'+result.rows[0].movie+'</li>');
        done();
      });
    }
  });
});

The same HTML escaping warning applies here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM