2

I have a module I need to export, but I want to export it after all async operations have finished. Essentially, I need the exported module to be "async ready" at the time I export it

class Store {
   async dummy() {
      await somethingElse()
   }
}

const store = new Store();

// at this point, before exporting it, I want to
await store.dummy()

// but since I am not in a function, I cannot await it
export { store }

Any ideas?

Zain Shaikh
  • 6,013
  • 6
  • 41
  • 66
Thomas
  • 4,641
  • 13
  • 44
  • 67
  • 5
    Module-level `await` is not possible for now. Your best bet will be to export the promise. – Bergi May 09 '18 at 12:48
  • Hm, interesting question. I wonder in what scenario you would really need to do this. – Hinrich May 09 '18 at 13:07
  • This is now possible, see the answers to the [linked question](https://stackoverflow.com/questions/46515764/how-can-i-use-async-await-at-the-top-level). – T.J. Crowder Oct 04 '22 at 09:43

3 Answers3

1

This is part of the red-blue problem we face in Javascript, and basically there isn't a good solution. Once you've introduced asynchronicity, you're async all the way. If you try to await, any function that awaits will be default be a promise factory. As was suggested your best bet is to return a promise, but without being able to do any kind of thread blocking you're stuck in promise land.

TheCog19
  • 1,129
  • 12
  • 26
1

Using await on a module scope is not possible at the moment of writing.

Try rewriting your module to export a method that will use the async/await functionality.


There is no option of mixing asynchronous and sequential code. You have to go all in! (As described in TheCog's answer: http://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/)

janniks
  • 2,942
  • 4
  • 23
  • 36
0

I was able to get away with it, but basically due to the use case I had Basically, I have a react application and the module in question is the one that initializes all of my stores and services

So I ended up solving it by awaiting it, when I import it and before passing it to the main react component

const load = async () => {
    const rootEl = document.getElementById('app');
    //below the solution
    **await bootstrap.RootStore.init();**
    routeInit(bootstrap.RootStore.getService('logger'), bootstrap.RootStore.UIStore);
    render(
        <Provider {...bootstrap}>
            <Router history={browserHistory} onUpdate={bootstrap.RootStore.UIStore.trackPage} routes={routes} />
        </Provider>,
        rootEl
    );
}

load();
Thomas
  • 4,641
  • 13
  • 44
  • 67