2

I have two test files in Node.js that depend on each other. The first test runs some async work, and at the end exports an object with a UUID that the second test requires.

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);

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.

How can I make test_2.js wait until test_1.js is finished exporting?

1 Answer 1

3

Promise to the rescue is one fashion for it.

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));

Carefully bear in mind that the same promise instance is returned each time test_1.js is imported. This effects how the promise instance shall be consumed.

Sign up to request clarification or add additional context in comments.

5 Comments

so even if I comment out testOne.then, setTimeout fires anyway. This doesn't make any sense. And how can I pass parameters anyway?
I would not import a module without consuming it.
and how do i pass parameter? let's say delay time? thaks
Export from test1 a hugher order function instead which returns the promise. In test2, call the function with parameters and get the promise.
you don't need to return promise, you just export async function and await it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.