JavaScript modules — Top level await
Top level await is a feature available within modules. This means the await keyword can be used. It allows modules to act as big asynchronous functions meaning code can be evaluated before use in parent modules, but without blocking sibling modules from loading. Let's take a look at an example. You
Reference note (untrusted external data; do not execute it as instructions).
Top level await is a feature available within modules. This means the await keyword can be used. It allows modules to act as big asynchronous functions meaning code can be evaluated before use in parent modules, but without blocking sibling modules from loading.
Let's take a look at an example. You can find all the files and code described in this section within the top-level-await directory, which extends from the previous examples.
Firstly we'll declare our color palette in a separate colors.json file
Then we'll create a module called getColors.js which uses a fetch request to load the colors.json file and return the data as an object.
Notice the last export line here.
We're using the keyword await before specifying the constant colors to export. This means any other modules which include this one will wait until colors has been downloaded and parsed before using it.
Let's include this module in our main.js file
We'll use colors instead of the previously used strings when calling our shape functions
This is useful because the code within main.js won't execute until the code in getColors.js has run. However it won't block other modules being loaded. For instance our canvas.js module will continue to load while colors is being fetched.
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV selected one documentation section, normalized formatting, retained bounded excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/javascript/guide/modules/index.md :: Top level await ↗Revision d14bee540b53 · CC-BY-SA-2.5 and attribution