简体   繁体   English

NodeJs Require 模块返回一个空对象

[英]NodeJs Require module returns an empty object

I'm using NodeJS 8 LTS.我正在使用 NodeJS 8 LTS。

I have 3 js scripts where:我有 3 个 js 脚本,其中:

// main.js
const dom = require ('./Domains/Domains');
const factory = require ('./Domains/Factory');
(async () => {
    const Domain = await factory.foo();  // <=== Error

})();

// Domains.js
class Domains {
    constructor (options = {}) {
        ....
    }
}
module.exports = Domains;

// Factory.js
const Domains = require('./Domains');
module.exports = {
   foo: async () =>{

      .... async stuff ...

     return new Domains();
    }
};

when I run main.js I get当我运行main.js我得到

(node:1816) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Domains is not a constructor
warning.js:18
(node:1816) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Debugging, I found that in Factory.js when it requires Domanis.js const Domains = require('./Domains');调试,我发现在Factory.js时候需要Domanis.js const Domains = require('./Domains'); it returns an empty object.它返回一个空对象。

Looking around on internet I found that it happens when there are a circular dependencies between modules ( Require returns an empty object ) but It doesn't seem the case here.在互联网上环顾四周,我发现当模块之间存在循环依赖关系时会发生这种情况( Require 返回一个空对象),但这里似乎并非如此。

Any idea?任何的想法?

Finally, I got the the issue's origin.最后,我得到了问题的起源。 The empty object was due to a circular dependency derived by another require that was inside Domains.js空对象是由于由Domains.js另一个需求派生的循环依赖

// Domains.js
const another_module= require("circular_dep_creator");
class Domains {
    constructor (options = {}) {
        ....
    }
}
module.exports = Domains;

// circular_dep_creator.js
const factory = require ('./Domains/Factory');
...
another stuff

So, this causes a circular dependency that creates an empty object因此,这会导致创建一个空对象的循环依赖

The setImmediate call will delay the loading of the required module until the browser has finished doing what it needs to do. setImmediate调用将延迟加载所需模块,直到浏览器完成它需要做的事情。 This may cause some issues where you try to use this module before it is loaded, but you could add checks for that.这可能会导致您在加载之前尝试使用此模块时出现一些问题,但您可以为此添加检查。

// produces an empty object
const module = require('./someModule');

// produces the required object
let module;
setImmediate(() => {
  module = required('./someModule');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM