【发布时间】:2019-02-23 12:34:12
【问题描述】:
我正在使用 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),但这里似乎并非如此。
有什么想法吗?
【问题讨论】:
-
简而言之:当循环依赖发生时,Node 会创建空对象。然后,您必须通过动态获取依赖项或其他方式找到出路。此外,您可以使用名为 madge 的 npm 包检测循环依赖关系,使用
npx madge --circular <app entry point>这是一个可以提供帮助的视频:youtube.com/watch?v=JQQX62cUaYw
标签: node.js