【问题标题】:How to pass object from one file to another in javascript?如何在javascript中将对象从一个文件传递到另一个文件?
【发布时间】:2020-08-20 12:38:02
【问题描述】:

我有节点 js 服务器文件 (index.js) 和客户端文件 (orderlist.js) 在 index.js 中,我得到了 promise 对象,就像那样

function returnOrderArray() {
    var i = 0;
    const promise = new Promise((resolve, reject) => {
        connection.query('SELECT * FROM orders', function(error, results) {
            while (i < results.length) {

                order.id[i] = results[i].id;
                order.wavetype[i] = results[i].wavetype;
                order.color[i] = results[i].color;
                order.thick[i] = results[i].thick;
                order.readydate[i] = results[i].readydate;
                order.createdate[i] = results[i].createdate;
                order.manager[i] = results[i].manager;

                i++;
            }
            resolve(order);
            // console.log(order);


        });
    });
    return promise;
}

然后我想将它传递给其他 js 文件。 我尝试使用 module.exports 来做到这一点

app.get('/orderlist', checkUserSession, async function(request, response) {
    returnOrderArray().catch(error => console.log(error)).then((() => {
        module.exports.order = order;
        response.render("orderlist.ejs", { username: request.session.username });
    })).catch(error => console.log(error));
});

然后在 orderlist.js 中导入

var ind = require('../../index')


function asd() {
    alert(ind.order);
}

但它似乎不起作用。

我做错了什么,以及在 js 中将对象传递给其他文件的最佳方式是什么?

哦,还有文件架构

filearch

【问题讨论】:

  • 如果一个文件用在服务器端,另一个文件用在用户客户端,你怎么能指望它们互相导入呢?它们只能通过网络进行通信,使用 HTTP 请求或更高级的解决方案,例如 websockets

标签: javascript node.js web


【解决方案1】:

你需要像这样export你的模块:module.exports = returnOrderArray

试试这个,

orderlist.js

const returnOrderArray = () => {...some code..}
module.exports = returnOrderArray

index.js

const returnOrderArray = require('./path/to/orderlist.js')

const run = async() => {
const orderlist = await returnOrderArray() // use await or then as you prefer
}
run()

async_await 链接如果好奇!

希望这会奏效:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2020-07-10
    相关资源
    最近更新 更多