javascript - 将值分配给稍后将在不同脚本调用中使用的变量的正确方法是什么?
问题描述
有以下代码
连接.js
import pkg from "pg";
const { Client } = pkg;
let connection = undefined;
export async function connect() {
const client = new Client({
user: "postgres",
host: "localhost",
database: "dbname",
password: "password",
port: "5432",
});
connection = await client.connect();
}
export async function query(text, values) {
try {
await connection.query(text, values);
} catch (error) {
console.error(error.message);
}
}
我打算在调用connect
函数时为变量分配一个值connection
,然后在query
函数中使用该变量
这就是我调用连接方法的方式
index.js
import { connect } from "./src/connection.js";
import { handleStep1 } from "./src/step1.js";
async function init() {
await connect();
await handleStep1();
}
init();
我打算从另一个文件中调用查询函数,如下所示
step1.js
import { query } from "./connection.js";
export async function handleStep1() {
const results = await query("SELECT * FROM public.user", []);
console.log(results);
}
但是在这里调用查询函数时,它给了我以下错误消息Cannot read property 'query' of undefined
将值分配给稍后将在不同脚本调用中使用的变量的正确方法是什么?
提前致谢
解决方案
您可以简单地导出一个已初始化的变量并将其导入您想要的任何位置。
export async function connect() {
const client = new Client({
user: "postgres",
host: "localhost",
database: "dbname",
password: "password",
port: "5432",
});
connection = await client.connect();
}
export async function query(text, values) {
try {
await connection.query(text, values);
} catch (error) {
console.error(error.message);
}
}
// export let connection = connect();
// import it in other files. like import{ connection } from from "./connection.js";
//if you need to all connect only once. just update the line to
let connection = connect(); //remove the connection imports in other files.
推荐阅读
- javascript - 我正在使用 Photo Sphere Viewer,现在我想在不重新加载页面的情况下将全景图像替换为新图像
- php - 按类别对查询结果进行分页
- rabbitmq - 启动服务时 RabbitMQ 虚拟主机错误
- hibernate - 构建/码头化具有数据库连接的springBoot应用程序的最佳实践是什么?
- ios - 在 iOS 中以编程方式实现指南访问
- php - PHP 和魔术方法进入自己的类
- css - 如何使用 OpenStreetMap 和 OpenLayers 应用 css
- sql - Parse below XML in Sql Server
- c# - 颜色 TextBlock 取决于枚举值
- css - 应用的动画不在 IE 11 中运行