【问题标题】:Use functions fron another file, without require使用另一个文件中的函数,而不需要
【发布时间】:2021-02-01 15:39:21
【问题描述】:

上下文:

我有 3 个文件,parent.jschild1.jschild2.js

parent.js

let child1 = require("./child1.js")
let child2 = require("./child2.js")
let key = "*****"

child1.start(key)
child2.start();

child1.js

let key = false;

module.exports = {
    action: async() => {
        return someApi.get(key);
    },
    start: async(_key) => {
        key = key;
    }
}

child2.js

module.exports = {
    action: async() => {
        let res = await child1.action()
        ...
    },
    start: async() => {
        // startup actions
    }
}

问题

我需要在child2 中从child1 运行一个函数,但我不能使用require,因为只能有一个child1 的实例

有人知道解决办法吗?谢谢

【问题讨论】:

    标签: javascript node.js node-modules server-side


    【解决方案1】:

    我认为你问错了问题:)
    如果您需要 child1 是唯一的,您应该使用单音并在需要的任何地方都需要它。

    //child1
    let instance
    
    module.export = () => {
      if(!instance) {
         instance = {
        action: async() => {
            return someApi.get(key);
        },
        start: async(_key) => {
            key = key;
        }
       }
       return instance
    }
    

    我个人不喜欢单音方法,但它可以很方便

    您可以尝试的另一种方法是将 child1 服务实例注入 child2 'constructor'
    您只需导出一个函数而不是一个对象
    parent.js

    let child1 = require("./child1.js")()
    let child2 = require("./child2.js")(child1)
    let key = "*****"
    
    child1.start(key)
    child2.start();
    

    child2

    module.exports = (child1) => {
        
        const action =  async() => {
            let res = await child1.action()
            ...
        }
        const start =  async() => {
            // startup actions
        }
        return {action, start}
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-26
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2013-03-06
      • 2016-06-21
      • 1970-01-01
      相关资源
      最近更新 更多