[英]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. 我正在尝试给自己一个实践,将纯节点用作服务器,并使用PG连接到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.
因此,如何从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. 请注意,这只是一个示例,您实际上应该在输出之前进行HTML转义。
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. 另外,如果您要响应请求并使用Express,则可以简单地传递响应对象并调用其方法之一。 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. 相同的HTML转义警告在此处适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.