Sub topic 7
Loading Several Modules at Once
This chapter assumes you already know how import() returns a promise for a module namespace object, how to destructure named and default exports from it, and how to catch a failed import with try/catch. It also assumes you are comfortable with Promise.all from general async/await work. The focus here is narrower: when your code needs more than one module at runtime, how do you avoid loading them one after another?
The Hidden Cost of Sequential Awaits
The most natural way to write two dynamic imports is to put one await after the other:
async function run() {
const { parse } = await import('./parser.js');
const { format } = await import('./formatter.js');
console.log(format(parse('2 + 2')));
}
run();This code is correct, but it is slow. The second import() call does not even start until the first promise settles. In a browser, each import can involve a network round trip for the module itself and then more round trips for its static dependencies. If parser.js takes 200 ms to arrive and formatter.js takes 150 ms, the user waits about 350 ms, even though nothing in formatter.js depends on parser.js.
The fix is to start both imports before awaiting either. An import() call begins fetching as soon as it is evaluated. The await only decides when your code pauses to read the result.
Starting Imports Together with Promise.all
Promise.all takes an array of promises and resolves to an array of their results in the same order. Because the import() calls inside the array literal all run before Promise.all is awaited, the runtime fetches the modules concurrently:
async function run() {
const [{ parse }, { format }] = await Promise.all([
import('./parser.js'),
import('./formatter.js'),
]);
console.log(format(parse('2 + 2')));
}
run();The total wait is now roughly the time of the slowest module, about 200 ms in the example above, rather than the sum.
The results array follows the order of the input array, not the order in which the modules finish loading. Even if formatter.js arrives first, the first element is still the parser.js namespace. That makes the destructuring pattern safe.
Measuring the Difference
Local files in Node.js load too quickly to show the effect, so the script below adds an artificial delay before each import. Save it as timing.mjs next to two small modules, then run node timing.mjs.
// parser.js
export function parse(text) {
const [a, op, b] = text.split(' ');
return { a: Number(a), op, b: Number(b) };
}// formatter.js
export function format({ a, op, b }) {
const result = op === '+' ? a + b : NaN;
return `${a} ${op} ${b} = ${result}`;
}// timing.mjs
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Simulates a module that takes `ms` milliseconds to arrive over the network.
async function slowImport(specifier, ms) {
await delay(ms);
return import(specifier);
}
async function sequential() {
const start = performance.now();
const { parse } = await slowImport('./parser.js', 200);
const { format } = await slowImport('./formatter.js', 150);
console.log(format(parse('2 + 2')));
console.log(`sequential: ${Math.round(performance.now() - start)} ms`);
}
async function parallel() {
const start = performance.now();
const [{ parse }, { format }] = await Promise.all([
slowImport('./parser.js', 200),
slowImport('./formatter.js', 150),
]);
console.log(format(parse('2 + 2')));
console.log(`parallel: ${Math.round(performance.now() - start)} ms`);
}
async function main() {
await sequential();
await parallel();
}
main();On a typical machine you will see something like sequential: 352 ms and parallel: 201 ms. If the .js files are not treated as ES modules in your folder, add a package.json containing { "type": "module" }, or rename them to .mjs and update the specifiers.
Shared Dependencies Are Fetched Once
Suppose parser.js and formatter.js both statically import ./tokens.js. Loading the two in parallel does not fetch or evaluate tokens.js twice. The module loader keeps a map from resolved URL to module record. The first request creates the entry, and any concurrent request for the same URL waits on that same entry. tokens.js is evaluated once, before whichever of its importers is evaluated first.
The same rule covers calling import() twice with the same specifier at the same moment:
async function run() {
const [a, b] = await Promise.all([
import('./parser.js'),
import('./parser.js'),
]);
console.log(a === b); // true: one module instance, one namespace object
}
run();This means you don't need your own "is it already loading?" flag around import(). The runtime already deduplicates requests.
Choosing a Combinator
Promise.all rejects as soon as any input rejects. That fits modules your feature cannot work without. For optional modules, such as plugins, analytics, or extra locale data, a failed import should not throw away the modules that succeeded. Other promise combinators handle those cases.
| Combinator | Settles when | Good for |
|---|---|---|
| `Promise.all` | All succeed, or the first one fails | Modules that are all required |
| `Promise.allSettled` | Every import has succeeded or failed | Optional plugins where partial success is fine |
| `Promise.any` | The first success, or all fail | Mirrors or fallback CDNs serving the same module |
| `Promise.race` | The first settlement, success or failure | Racing an import against a timeout |
Here is a plugin loader built on Promise.allSettled:
// plugins/upper.js
export default function upper(text) {
return text.toUpperCase();
}// plugins/exclaim.js
export default function exclaim(text) {
return `${text}!`;
}// load-plugins.mjs
const pluginNames = ['upper', 'exclaim', 'missing'];
async function loadPlugins(names) {
const results = await Promise.allSettled(
names.map((name) => import(`./plugins/${name}.js`))
);
const plugins = [];
results.forEach((result, i) => {
if (result.status === 'fulfilled') {
plugins.push(result.value.default);
} else {
console.warn(`Plugin "${names[i]}" failed:`, result.reason.message);
}
});
return plugins;
}
async function main() {
const plugins = await loadPlugins(pluginNames);
const output = plugins.reduce((text, plugin) => plugin(text), 'hello');
console.log(output); // HELLO!
}
main();The missing plugin logs a warning, and the other two still run. Because results has the same order as names, the index i links each failure back to its plugin name.
Starting Loads Earlier
Parallel loading is about overlapping waits, and you can overlap a load with user activity as well as with other loads. Store the promise when the load becomes likely, and await it when the result is actually needed:
const button = document.querySelector('#open-editor');
let editorPromise = null;
function preloadEditor() {
editorPromise ??= Promise.all([
import('./editor.js'),
import('./toolbar.js'),
]);
return editorPromise;
}
// Start fetching when the user shows intent.
button.addEventListener('pointerenter', preloadEditor, { once: true });
button.addEventListener('focus', preloadEditor, { once: true });
button.addEventListener('click', async () => {
const [{ createEditor }, { createToolbar }] = await preloadEditor();
const root = document.querySelector('#editor-root');
createToolbar(root);
createEditor(root);
});By the time the click handler runs, the modules have often already arrived. If a preload fails, that stored promise stays rejected. To retry, reset editorPromise to null in a catch block.
In browsers, <link rel="modulepreload" href="/editor.js"> in the HTML gives a similar head start before any script runs. Bundlers can emit these hints for you, which a later chapter covers.
Common Mistakes
- Awaiting inside a loop.
for (const n of names) { mods.push(await import(n)); }loads the modules one at a time. Map the names to promises first, then await them all together. - Wrapping already-awaited values.
Promise.all([await import('./a.js'), await import('./b.js')])is still sequential, because eachawaitruns while the array is being built. - Using
Promise.allfor optional modules. A single missing plugin rejects the whole batch. UsePromise.allSettledinstead. - Expecting a parallel speedup in Node.js for local files. Reading from disk is fast, so the gain is small. The pattern matters most for network loads in browsers, or for modules whose top-level code does slow work.
- Opening too many requests at once. Loading 200 modules in parallel can saturate connections and delay the important ones. Load only what the current screen needs, or process large lists in batches.
Exercise
A teammate writes const mods = []; for (const lang of ['en', 'fr', 'de']) { mods.push(await import(./locales/${lang}.js)); }. Each locale file takes about 100 ms to load over the network. Roughly how long does this take, and how would you rewrite it so the three files load concurrently?
Show answer
About 300 ms, because each import starts only after the previous one finishes. Rewrite it as const mods = await Promise.all(['en', 'fr', 'de'].map((lang) => import(./locales/${lang}.js)));. All three imports start right away, so the total is about 100 ms, and mods keeps the order en, fr, de.
Exercise
Two modules, a.js and b.js, are loaded with Promise.all([import('./a.js'), import('./b.js')]). Both statically import shared.js, which runs console.log('shared') at the top level. How many times is "shared" printed, and is the output order of any logs in a.js and b.js guaranteed?
Show answer
"shared" is printed once, because the loader caches one module record per resolved URL and evaluates it a single time. The relative order of a.js and b.js top-level code is not guaranteed. It depends on which graph finishes loading first. The only guarantee is that shared.js runs before each module that imports it.
Exercise
You load five analytics integrations with Promise.all, and one CDN is down. What happens to the other four, and which combinator would make the page keep the working ones?
Show answer
The Promise.all promise rejects with the first error, so your code never receives the four namespaces that loaded. Those modules still finish loading and run their top-level code, because rejection does not cancel them. Promise.allSettled returns a status for every import, so you can use the fulfilled ones and log the failure.