简体   繁体   English

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

[英]Async module.exports dependency in Node.js

I have two test files in Node.js that depend on each other. 我在Node.js中有两个相互依赖的测试文件。 The first test runs some async work, and at the end exports an object with a UUID that the second test requires. 第一个测试运行一些异步工作,最后输出带有第二个测试所需的UUID的对象。

test_1.js test_1.js

'use strict';

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

test_2.js test_2.js

'use strict';

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

The problem is since the module.exports is called async in the first test, in test two console.log(testOne) is just an empty object. 问题在于,在第一个测试中, module.exports被称为异步,在第二个测试中, console.log(testOne)只是一个空对象。

How can I make test_2.js wait until test_1.js is finished exporting? 如何让test_2.js等到test_1.js完成导出?

Promise to the rescue is one fashion for it. 对救援的承诺是它的一种方式。

test_1.js test_1.js

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

test_2.js test_2.js

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

Carefully bear in mind that the same promise instance is returned each time test_1.js is imported. 请注意,每次导入test_1.js时, 都会返回相同的promise实例。 This effects how the promise instance shall be consumed. 这影响了如何使用promise实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM