类不是构造函数,多个“需要”

时间:2019-08-06 16:27:04

标签: javascript node.js

我正在使用“状态”类,它具有模型和控制器文件。但是,在我的主应用程序(app.js)上导入这些类时,似乎存在冲突,因为app.js和state.controller.js中都“需要”“ state.model.js”。因此,给我一个错误,State不是构造函数。

app.js:

.part.lock

state.controller.js:

const State = require('./model/state.model');
const stateController = require('./controller/state.controller');

stateController.insert(msg, State.STATE_REMINDER.name, State.STATE_REMINDER.key.day, selected_day, (err, doc) => {
            if (err) throw err;
            console.log("[STATE][INSERT]", doc);
        });

state.model.js:

const Database = require('../database');
const State = require('../model/state.model');
const db = Database.collection('states');

db.loadDatabase((err) => {
    if (err) throw err;
    console.log("[STATES] Database connected");
});

exports.insert = (msg, state, key, value, callback) => { // msg refers to Telegram Callback
    let insertState = new State(undefined, msg.from.id, msg.chat.id, state, key, value);
    console.log(insertState);
    db.insert(insertState, (err, newDoc) => {
        if (err) throw err;
        callback(err, newDoc);
    });

};

当我将app.js中的代码顺序交换为:

时,此问题实际上已解决。
const stateController = require('../controller/state.controller');

const STATE_REMINDER = {
    name: "STATE_REMINDER",
    key: {
        day: "DAY",
        time: "TIME"
    }
};

class State {
    constructor(id, user_id, chat_id, state, key, value) {
        this._id = id;
        this.user_id = user_id;
        this.chat_id = chat_id;
        this.state = state;
        this.key = key;
        this.value = value;
        this.timestamp = new Date();
    }

    static get STATE_REMINDER() {
        return STATE_REMINDER;
    }
}

module.exports = State;

为什么会这样?任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

您的代码具有循环依赖循环:

app.js需要state.model.js,而state.controller.js需要state.model.js,而state.controller.js等等等

在这种情况下,require将检测到循环依赖并且不会永远持续下去。但是,这意味着在某个时候它将仅返回“ null”而不是实际的类。它可能看起来像这样:

app.js->需要state.model.js

state.model.js->需要state.controller.js

state.controller.js->需要state.model.js。此时,节点将检测到循环,并将为state.model.js返回null,然后开始展开堆栈。

我不确定切换顺序时为什么它会起作用,循环仍然存在,并且应该仍然引起问题,这可能是节点导入文件的方式有些奇怪。