await
is a keyword used in async
functions. Currently await
is only used inside the async
function. If you use outside async
, throws an error.
With the ES13 release, You can use await without async context.
Await can be used in multiple ways.
ES13 Top-level await
top-level await used in different use cases.
Load modules at runtime
await
is used with top-level ESM modules using imports only.
Modules won’t complete loading until await promise is settled. Resolved means successful loading module, and rejected means failed to load a module.
const modules = await import(`./modules`);
- use await in a plain script tag:
You can use await in plain script tags.
<script>
await Promise.resolve('Resolved');
console.log('load completed');
</script>
It throws “SyntaxError: await is only valid in async functions and the top level bodies of modules
To make await work in a plain script tag, add type=“module”.
<script type="module">
await Promise.resolve('Resolved');
console.log('load completed');
</script>
- use await in fallback for module failure We can use await for fallback use cases where the module failed to load with try-and-catch blocks.
let module;
try {
module = await import("./module.esm");
} catch {
module = await import("./module.esm");
}
- initialization during loading
await can be used to call database-related code to initiate a connection.
const connection = await loadMongoDB();
Important notes:
- It works top-level modules using ES6 modules(esm)
- No Support for plain
<script>
tags, But you have to use<script type="module">
to make it work.