0

In my main JavaScript file I've imported an ECMASCript module (a separate file named module.js). In the main file, is there any way to import the module, then pause execution of of the main file until all code in the module has been executed, then resume execution of the remaining lines in main.js?


My Code

main.js

import { hello } from './module.js';
console.log(hello());
console.log('Print this after Hello World.');

module.js

import fetch from 'node-fetch';// Needed in order to use fetch() in Node.

export function hello() {

  fetch('http://example.com/movies.json')
  .then((response) => {
    return 'Hello World!';
  });

}

Desired Output

Hello World!
Print this after Hello World.

Actual Output

undefined
Print this after Hello World.

Attempted Solution: promise

If I try to wrap the import and console.log() lines in a promise, I encounter a JS console error saying import must be in the top level of a file only.

edit: It seems like I could perhaps wrap hello() in a promise, and use a then to execute code after the promise is resolved?

Possible Solution: async/await

Could I use async/await in main.js to ensure script execution paused until the code in the module was complete? The import line would remain in the top level of the file, correct?

Thanks.

cag8f
  • 817
  • 1
  • 10
  • 33

0 Answers0