Home > Enterprise >  Do promises resolved during module init run before scripts (with top level await?)
Do promises resolved during module init run before scripts (with top level await?)

Time:11-26

When using webpack (v5 via webpacker v6) and exporting an interface (e.g. via globals) to other scripts on a webpage do promises resolved during module initialization necessarily execute before the scripts on the page access them? Is there a way to ensure they do? Would top level await work?

Specifically, imagine I have a module that's exported to the global Library FOO that loos like the following

---In module getting webpacked---
class Foo { ... }
const done = (async function()  {
    Foo.bar = 10 - (await prom)/(await other_prom)
})()
resolve(5); other_resolve(80); //resolve for prom/other_prom
await done //if we have top level await
export {Foo}
--- In (unprocessed) script tag later ---
new FOO.Foo(20);  //This shouldn't execute until AFTER the async function modifies Foo

I'd like new FOO.Foo(20) to be guaranteed not to executed until after the async function up above completes executing. Is there a way to be guaranteed this won't be executed before the initialization is done other than wrapping all page javascript in an async function and awaiting all the initializing promises? At that point I might as well just give up on the niceties of async and write callback functions.

CodePudding user response:

exporting an interface via globals to other scripts on a webpage

No, don't do that. It's neither a good practice to use globals, nor will top-level-await make anything wait. And non-module scripts can't use top-level-await anyway.

Instead, if you do use modules like

export class Foo { ... }
Foo.bar = 10 - (await Promise.resolve(5)/(await Promise.resolve(80));
import * as FOO from 'the-first-module';
new FOO.Foo(20);

then yes, it will work as expected and not run new Foo before the imported script has finished its asynchronous evaluation.

  • Related