Dynamic Import with Async/Await
You'll learn how to write cleaner dynamic import code using async/await instead of promise chains.
In the previous lesson, you saw dynamic imports return promises, which you handled with .then() and .catch(). Since you're now comfortable with async/await, you can write dynamic imports in a much more readable way.
The Cleaner Approach
Instead of chaining .then() calls, you can use await to pause execution until the module loads, then work with it directly:
async function loadUserModule() {
try {
const userModule = await import('./user.js');
const user = new userModule.User('Alice');
return user;
} catch (error) {
console.error('Failed to load user module:', error);
}
}
Why This Is Better
Compare the async/await version to the promise chain:
// Promise chain version
function loadModule() {
import('./module.js')
.then(module => {
return module.doSomething();
})
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
}
// Async/await version
async function loadModule() {
try {
const module = await import('./module.js');
const result = module.doSomething();
console.log(result);
} catch (error) {
console.error(error);
}
}
The async/await version reads like synchronous code, making it easier to understand the flow and handle multiple dynamic imports sequentially or in parallel.
Think of It This Way
It's like ordering food delivery: instead of setting up callbacks for "when food arrives, then eat it, then clean up," you can write "wait for food to arrive, eat it, clean up" — one clear step after another.
Key Takeaway: Use async/await with dynamic imports for cleaner, more readable code that handles module loading errors with familiar try/catch syntax.