Sub topic 7
Loading Several Modules at Once
This chapter assumes you already know how import() returns a promise for a module namespace object, and that you are comfortable with Promise.all and async/await. It shows how to load several modules without making each one wait for the one before it.
The cost of awaiting one at a time
When a feature needs two modules, the obvious code awaits them in turn:
const { parse } = await import('./parser.js');
const { format } = await import('./formatter.js');
console.log(format(parse('2 + 2')));This works, but it is slower than it needs to be. The second import() call does not start until the first promise has settled. In a browser, that means one network round trip finishes before the next begins. If each module takes 150 ms to fetch, the user waits about 300 ms in total.
Neither module depends on the other here, so nothing requires this ordering. The await keyword creates it.
Start every import, then await together
An import() call starts fetching as soon as it runs. To load in parallel, call every import() first and then wait for all of them with Promise.all:
const [{ parse }, { format }] = await Promise.all([
import('./parser.js'),
import('./formatter.js'),
]);
console.log(format(parse('2 + 2')));Promise.all resolves to an array of namespace objects in the same order as the input array, whatever order the modules finish in. Array destructuring then pulls the named exports out of each namespace.
With parallel loading, total wait time is roughly the time of the slowest module, not the sum of all of them.
When one module may fail
Promise.all rejects as soon as any input rejects. That fits modules your code cannot run without. For optional modules, use Promise.allSettled, which waits for every promise and reports each outcome:
const results = await Promise.allSettled([
import('./core.js'),
import('./analytics.js'),
]);
const [coreResult, analyticsResult] = results;
if (coreResult.status === 'rejected') {
throw coreResult.reason;
}
const core = coreResult.value;
const analytics =
analyticsResult.status === 'fulfilled' ? analyticsResult.value : null;
core.start({ analytics });Each result has a status of 'fulfilled' or 'rejected', with either a value (the namespace object) or a reason (the error).
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Awaiting each `import()` on its own line | Fetches run one after another | Pass all the calls to `Promise.all` |
| Writing `Promise.all([await import(a), await import(b)])` | The inner `await`s make it sequential again | Remove the inner `await` keywords |
| Using `Promise.all` for optional modules | One missing module rejects the whole batch | Use `Promise.allSettled` |
| Expecting results in completion order | Wrong export assigned to the wrong name | Results follow input order |
Exercise
This code loads three independent modules. Rewrite it so they load in parallel, keeping the same variable names: const a = (await import('./a.js')).default; const b = (await import('./b.js')).default; const c = (await import('./c.js')).default;
Show answer
const [{ default: a }, { default: b }, { default: c }] = await Promise.all([import('./a.js'), import('./b.js'), import('./c.js')]); All three fetches start before any await, and destructuring with default: renames each default export.
Exercise
You load charts.js (required) and tooltips.js (nice to have) with Promise.all. A deploy breaks tooltips.js, and now charts stop rendering too. Why, and what should you change?
Show answer
Promise.all rejects as soon as any promise rejects, so the failed tooltips import rejects the whole call and the charts code never runs. Switch to Promise.allSettled, rethrow if charts.js was rejected, and treat a rejected tooltips.js as missing.