IIFE Async Functions
You'll learn how to use immediately-invoked async function expressions to await at the top level in older JavaScript environments.
What's the Problem?
In older JavaScript environments (before ES2022's top-level await), you couldn't use the await keyword outside of an async function. But sometimes you need to perform async operations immediately when a script runs—like fetching data on page load or reading a config file.
The Solution: Wrap and Invoke
An IIFE (Immediately Invoked Function Expression) async function is an async function that you define and call in one expression. You wrap your async code in an async function and immediately execute it.
The Pattern
(async () => {
// Now you can await here at the "top level"
const result = await someAsyncOperation();
console.log(result);
})();
Notice the structure: (async () => { ... })() — you define an async arrow function inside parentheses, then immediately invoke it with ().
Why It Works
Since async functions return promises, you're essentially creating and starting a promise-based workflow right away. The outer code continues normally, while your IIFE runs asynchronously.
Real-World Example
(async () => {
try {
const user = await fetchUser(123);
const posts = await fetchPosts(user.id);
console.log(`${user.name} has ${posts.length} posts`);
} catch (error) {
console.error('Startup error:', error);
}
})();
This pattern lets you write clean sequential async code at module initialization without wrapping everything in named functions.
Key Takeaway: Use (async () => { await ... })() to run async code immediately in environments without top-level await—it's like creating a little async sandbox at the top of your script.