Hacker News new | ask | show | jobs
by Scooty 2457 days ago
Top level await does more than remove a main function. If you import modules that use top level await, they will be resolved before the imports finish.

To me this is most important in node where it's not uncommon to do async operations during initialization. Currently you either have to export a promise or an async function.

3 comments

Do we really want slow imports though? If you have a bunch of modules with async setup functions, would you not be able to Promise.all() them?
That kinda stuff is typically an antipattern in C#; an async static "factory method" would be used(I use this pattern myself in Typescript). But I guess JavaScript has odd stuff like code chunking so the importau be pulling remote code and etc.
Sure, in many situations, but I guess if you need to setup things have have dependencies (init A then init B then init C) this will help.
How so? I'm not seeing the benefit over exporting A, B, and C as functions, and then putting them together in another spot (like a composite root for pure DI, or an IoC container, etc).

Is the argument for top-level await that you don't need the other spot? Because I feel like you still do - except now it's implicitly inside not only A, but likely B and C as well to some extent. And in a very inflexible way.

No one should be asynchronously executing code on import? I'd rather my code call a function to kick it off.
Please, this.

Synchronous effectful imports are already are the source of so much frustration, and now we're adding asynchronicity to it?

Just export a init function and let your users choose when/where to run your effectful initialization code, sync or async.

Oh that's interesting if this is the case. So now a module export can contain an asynchronously initialized db handler for example?
Please don't do that though!