我正在使用 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时.jsconst Domains = require('./Domains');
它会返回一个空对象。
在互联网上环顾四周,我发现当模块之间存在循环依赖关系时就会发生这种情况(Require返回一个空对象(,但这里似乎并非如此。
知道吗?
最后,我得到了问题的起源。空对象是由于内部的另一个需求派生的循环依赖关系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
因此,这会导致创建空对象的循环依赖项
setImmediate
调用将延迟所需模块的加载,直到浏览器完成它需要做的事情。这可能会导致一些问题,即在加载此模块之前尝试使用此模块,但您可以为此添加检查。
// produces an empty object
const module = require('./someModule');
// produces the required object
let module;
setImmediate(() => {
module = required('./someModule');
});