FrontendDeveloper.in

ECMAScript question detail

Top-level await

In ES2022, it is possible to use await outside of the asynchronous (async) function scope, which makes it easier to use at the module level. This feature delays the execution of current and parent modules until the imported module is loaded.

Let's take an example of await usage prior to ES2022,

import posts from './posts';

const getPosts = async() => {
let posts = await posts();
return posts;
}

The usage of await is straightforward with ES2022 as below,

let posts = await posts();

There are few use cases to know the benefits of this top-level await.

Usecases

  1. Dynamic dependency pathing: When you have a dynamic path for a dependency that depends on a runtime value, then await is helpful to load or import the messages at runtime.
const messages = await import(`./messages-${language}.js`);
  1. Dependency fallbacks: If the imported module is failed to load, then fallback module loaded used to load the dependency.
let lodash;
 try {
lodash = await import('https://first.domain.com/lodash');
 } catch {
lodash = await import('https://second.domain.com/lodash');
 }
  1. Resource initialization: This feature can be used to initialize an app with Database.
import { dbConnector} from './dbUtils.js'
//connect to database
const connection = await dbConnector.connect();
export default function(){
connection.list()
}
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399