How to deal with cyclic dependencies in Node.js

后端 未结 13 1974
别那么骄傲
别那么骄傲 2020-11-22 04:36

I\'ve been working with nodejs lately and still getting to grips with the module system so apologies if this is an obvious question. I want code roughly like the following b

13条回答
  •  后悔当初
    2020-11-22 05:07

    Here is a quick workaround that I've found use full.

    On file 'a.js'

    let B;
    class A{
      constructor(){
        process.nextTick(()=>{
          B = require('./b')
        })
      } 
    }
    module.exports = new A();
    

    On the file 'b.js' write the following

    let A;
    class B{
      constructor(){
        process.nextTick(()=>{
          A = require('./a')
        })
      } 
    }
    module.exports = new B();
    

    This way on the next iteration of the event loop classes will be defined correctly and those require statements will work as expected.

提交回复
热议问题