首页 > 解决方案 > 将值分配给稍后将在不同脚本调用中使用的变量的正确方法是什么?

问题描述

有以下代码

连接.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

将值分配给稍后将在不同脚本调用中使用的变量的正确方法是什么?

提前致谢

标签: javascriptnode.js

解决方案


您可以简单地导出一个已初始化的变量并将其导入您想要的任何位置。


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.



推荐阅读