NodeJs Require模块返回一个空对象

时间:2018-09-19 10:46:56

标签: node.js

我正在使用NodeJS 8 LTS。

我有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();
    }
};

我跑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.

调试时,我发现在Factory.js中需要Domanis.js const Domains = require('./Domains');时,它返回一个空对象。

环顾互联网,我发现当模块之间存在循环依赖关系(Require returns an empty object)时会发生这种情况,但在这里似乎并非如此。

有什么主意吗?

2 个答案:

答案 0 :(得分:2)

最后,我知道了问题的出处。空对象归因于16dp

内另一个需求派生的循环依赖关系
Domains.js

因此,这将导致循环依赖关系,从而创建一个空对象

答案 1 :(得分:-1)

这段代码对我有帮助:

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

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