Promises - Loading Multiple Files
A program often needs several files before it can start, such as a settings file and a data file, or a page’s stylesheets and scripts. If each load is a promise, Promise.all() can start them all together and wait until every one is ready. If any file fails, the whole load fails, and one catch() handles it.
Reading files in Node
Section titled “Reading files in Node”Node’s fs/promises module has promise-based versions of the file functions. This example reads two small JSON files. data/basket.json holds:
["bread", "milk", "apples"]and data/settings.json holds:
{ "currency": "GBP", "vatRate": 0.2 }const { readFile } = require('node:fs/promises');
const readJson = (path) => readFile(path, 'utf8').then((text) => JSON.parse(text));
Promise.all([readJson('data/settings.json'), readJson('data/basket.json')]) .then(([settings, basket]) => { console.log(`${basket.length} items, priced in ${settings.currency}`); }) .catch((error) => console.log('Could not load:', error.message));This prints:
3 items, priced in GBPIf one of the files is missing, the catch() callback receives the error. Node’s file errors carry a code property, so changing the second path to 'data/missing.json' and logging error.code in the catch() callback prints:
Could not load: ENOENTLoading stylesheets and scripts in the browser
Section titled “Loading stylesheets and scripts in the browser”A <link> or <script> element added to a page does not return a promise. It fires a load event when the file arrives and an error event when it cannot be loaded. A function can wrap those events in a promise, by calling resolve from the load listener and reject from the error listener:
<h1>Spring catalogue</h1><p id="status">Loading…</p><script src="load-files.js"></script>const loadElement = (element) => new Promise((resolve, reject) => { element.addEventListener('load', () => resolve(element)); element.addEventListener('error', () => reject(new Error(`Could not load ${element.href ?? element.src}`))); document.head.append(element); });
const loadStylesheet = (href) => loadElement(Object.assign(document.createElement('link'), { rel: 'stylesheet', href }));
const loadScript = (src) => loadElement(Object.assign(document.createElement('script'), { src }));
const status = document.querySelector('#status');
Promise.all([loadStylesheet('catalogue.css'), loadStylesheet('print.css'), loadScript('gallery.js')]) .then(() => { status.textContent = 'Everything has loaded.'; }) .catch((error) => { status.textContent = error.message; });When all three files load, the paragraph changes to “Everything has loaded.” If one of them is missing, it shows “Could not load” followed by that file’s address instead. The address is the full URL rather than the name passed in, because a link’s href property and a script’s src property both return the resolved URL.
The listeners are added before the element joins the page, so a file that loads very quickly cannot fire its event before anything is listening. A script added this way runs as soon as it loads, so scripts that depend on each other should be loaded one after another rather than with Promise.all().
For JavaScript modules, the dynamic import() function already returns a promise, so Promise.all([import('./a.js'), import('./b.js')]) loads several modules without any wrapping.
Steve Griffith covers this topic in his video Using Promise all to Load Multiple Files.