How to Use Top-Level Await in JavaScript?

Estimated read time 1 min read

Top-level await is a new feature introduced in ECMAScript 2022 (ES 2022) that allows you to use the await keyword outside of an async function. To use top-level await in JavaScript, you need to use a tool such as Babel or TypeScript to transpile your code, as it is not yet supported natively by most browsers and JavaScript engines. Here is an example of using top-level await in JavaScript:

(async () => {
  const response = await fetch('https://api.example.com');
  const data = await response.json();
  console.log(data);
})();

Note that top-level await is only allowed in modules, not in scripts. And also, when using top-level await, it is important to consider the implications of blocking the main thread, so use it with caution and only when necessary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply