0

我想module.exports.myInstance从其他文件中访问一个函数,如下所示。

// a.js
const func = async function () {
  ...
  module.exports.myInstance = ...;
}
func();

// b.js
const module = require("a.js").myInstance;
console.log(module);

我需要放入module.exports一个函数内部,因为我有一些东西可以使用 await 来获取myInstance。我试过这个并测试过,但我有undefinedwhen console.log(module). 这不是一种可能的格式吗?如果是,我应该怎么做才能完成这项工作?

4

1 回答 1

0

这是一个非常糟糕的模式..让它工作你应该写:

// a.js
const func = async function () {
  module.exports.myInstance = 'hello'
}
func()

// b.js
require('./a.js') // trigger the async function

// wait the loading with nextTick or setTimeout (if the operation takes longer)
process.nextTick(() => {
  // you must re-run the require since the first execution returns undefined!
  console.log(require('./asd.js').myInstance)
})

如您所见,基于时间和执行顺序的这段代码确实很脆弱。

如果你想要一个单例,你可以这样写:

// a.js
let cached
module.exports = async function () {
  if (cached) {
    return cached
  }
  cached = 'hello'
  return cached
}

// b.js
const factory = require('./a.js')

factory()
  .then(salut => { console.log(salut) })
于 2020-08-06T08:49:01.327 回答