- How the new ‘Top Level await’ feature works in JavaScript
- Kesk Noren
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: ssshooter
- Proofread by xionglong58 NiayYY-S
How to use the new feature “top-level await” in JavaScript
Short and effective JavaScript lesson, let you see the top-level await.
To use await previously, the related code must be inside the async function. In other words you cannot use await outside a function. The top-level await makes a module behave like an async function.
Modules are asynchronous and have import and export, which also exist at the top level. The practical implication of this is that if you want to provide a module that relies on other asynchronous tasks to do something, you really have no better choice.
The top-level await solves this problem by allowing developers to use the await keyword outside of async functions. With the top-level await, ECMAScript modules can wait for the resource to be fetched, causing other modules that import them to wait for the resource to be loaded before executing. It can also be used as a fallback for loading dependencies if the module fails to load or is used to load the first downloaded resource.
Note:
- Top-level await can only be used at the top level of a module and does not support traditional script tags or non-async functions.
- As of this writing (23/02/2020), this feature is on ECMAScript Stage 3.
Use the sample
With the top-level await, the following code will work normally in the module
1. Perform the rollback when the module fails to be loaded
The following example attempts to load a JavaScript module from first.com.
//module.mjs
let module;
try {
module= await import('https://first.com/libs.com/module1');
} catch {
module= await import('https://second.com/libs/module1');
}
Copy the code
2. Use the fastest loading resource
Here the initial value of the RES variable is determined by the download request that ends first.
//module.mjs
const resPromises = [
donwloadFromResource1Site,
donwloadFromResource2Site
];
const res = await Promise.any(resPromises);
Copy the code
3. Initialize resources
The top-level await allows you to await promises in modules as if they were wrapped in an async function. This is useful, for example, to initialize an application:
//module.mjs
import { dbConnector} from './dbUtils.js'
//connect() return a promise.
const connection = await dbConnector.connect();
export default function(){connection.list()}
Copy the code
4. Dynamically load modules
Allows modules to dynamically decide on dependent libraries.
//module.mjs
const params = new URLSearchParams(window.location.search);
const lang = params.get('lang');
const messages = await import(`./messages-${lang}.mjs`);
Copy the code
5. DevTools can also use await outside of async function?
SyntaxError: await is only valid in async function, but now it can be used normally.
DevTools tests for Chrome 80 and Firefox 72.0.2 worked. However, this feature is currently not standard and can no longer be used in NodeJS.
const helloPromise = new Promise((resolve) = >{
setTimeout((a)= > resolve('Hello world! '), 5000);
})
const result = await helloPromise;console.log(result);
//5 seconds later... :
//Hello world!
Copy the code
implementation
- V8 enable flag: — harmony-top-level-await
- WebPack (5.0.0 Experimental support)
- Babel supported (Babel /plugin-syntax-top-level-await)
The resources
- Github.com/bmeck/top-l…
- Github.com/tc39/propos…
Thanks for reading!
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.