【发布时间】:2019-12-26 21:03:21
【问题描述】:
我正在从数据库中提取一些数据,以便在我的 nodejs 应用程序中使用它。 我正在使用 node-postgres 连接到数据库 (https://node-postgres.com/)。
我多次阅读指南并尝试以不同方式查询它(回调、承诺、使用池和客户端),但总是出错。
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;
我可以在控制台输出中看到数据,所以连接正常,但是当我尝试运行代码时,我得到了
ReferenceError: projects is not defined.
感谢您对此提供的任何帮助。
【问题讨论】:
-
是的......这就是异步的工作原理:) 并非所有东西都始终可用。此外,您的
projects变量仅在回调中定义。 -
您在传递给
then的箭头函数内定义projects。由于 范围,它无法从外部访问 -
如果您需要异步导出某些内容,我认为 stackoverflow.com/questions/51142495/… 可能是您的解决方案
标签: javascript node.js postgresql asynchronous