top level await

Use await at the top level of modules without wrapping in an async function.

Explanation

  • await can now be used directly in module scope without an async function wrapper.
  • The module becomes asynchronous and other modules importing it will wait for it to resolve.
  • Simplifies initialization code that needs to wait for async operations.
  • Only works in ES modules, not in CommonJS or script tags without type="module".

Usage

To use await at the top level of your modules:

// config.js - Top-level await for configuration
const response = await fetch('/api/config');
const config = await response.json();

export default config;

// main.js - Using the config
import config from './config.js';

console.log(config.apiUrl); // Config is already loaded
console.log('App initialized with config');

// Dynamic imports with top-level await
const { default: lodash } = await import('lodash');
const data = lodash.chunk([1, 2, 3, 4, 5, 6], 2);