Node.js 中的异步 module.exports 依赖项

Async module.exports dependency in Node.js

我在 Node.js 中有两个相互依赖的测试文件。第一个测试运行一些异步工作,最后导出一个具有第二个测试所需的 UUID 的对象。

test_1.js

'use strict';

# simulate some async work
setTimeout(() => {
    module.exports = {
        id: '83b50527-73a9-4926-8247-e37547f3da6d'
    };
}, 2000);

test_2.js

'use strict';

const testOne = require('./test_1.js');
console.log(testOne);

问题是因为 module.exports 在第一个测试中被称为异步,在测试两个中 console.log(testOne) 只是一个空对象。

如何让 test_2.js 等到 test_1.js 完成导出?

承诺救援是一种时尚。

test_1.js

module.exports = new Promise(resolve => {
  setTimeout(() => resolve({
    id: '83b50527-73a9-4926-8247-e37547f3da6d'
  }), 2000);
});

test_2.js

const testOne = require('./test_1.js');
testOne.then(uuid => console.log(uuid.id));

请注意每次导入 test_1.js 时都会返回相同的 promise 实例。这会影响 promise 实例的使用方式。