Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C4 · Lekcja 9
ZadanieUse top-level await to await Promise.resolve('hello'), assign to const greeting, log it. Then await Promise.resolve(123), assign to const num, log 'num:', num.

Oczekiwanie na najwyższym poziomie: kiedy możesz pominąć IIFE

75 XP6 min
Teoria

The classic workaround

Before 2022 you couldn't await at the top of a file. So everyone wrote IIFEs:

(async () => {
  const r = await fetch("/api/user");
  const user = await r.json();
  console.log(user);
})();

It's just there to create an async scope. Five tokens of pure noise.

Top-level await — what every module gets

Inside any ES module (file with import / export, or <script type="module">), you can write:

const r = await fetch("/api/user");
const user = await r.json();
console.log(user);

The module load itself becomes async. Anything that imports this module waits until your top-level awaits finish. That's exactly what you want for "initialize the config before anyone uses it."

The cost

Top-level await delays the module's "done loading" event. If three modules each have a 500ms top-level await, the user sees nothing for 1.5s. So:

  • Use it for initialization that genuinely can't happen later (config from a fetch, WASM module compile, decryption key).
  • Avoid it for "would be nice to prefetch" stuff — do that lazily on first call instead.

What it doesn't do

Top-level await doesn't make sibling modules wait on each other unless they directly import each other. ES module loading is still parallel where it can be — top-level await just adds a "ready" gate on the importing side.

🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.