Reading Multiple Files Sequentially
You'll learn how to process multiple file uploads one at a time in order, rather than all at once or in random completion order.
When users select multiple files, you might be tempted to create a FileReader for each and start reading them all simultaneously. However, this can cause race conditions where files finish reading in unpredictable order, making it difficult to display progress, maintain file order, or process results sequentially.
The Sequential Pattern
The key is using a loop or recursion that waits for each file to finish reading before starting the next. Since FileReader is asynchronous, you need to handle its onload event before proceeding:
function readFilesSequentially(files) {
let index = 0;
function readNextFile() {
if (index >= files.length) {
console.log('All files read!');
return;
}
const file = files[index];
const reader = new FileReader();
reader.onload = function(e) {
console.log(`File ${index + 1}: ${file.name}`);
console.log('Result:', e.target.result.substring(0, 50) + '...');
index++;
readNextFile(); // Read next file only after this one completes
};
reader.readAsText(file);
}
readNextFile();
}
// Usage with file input
document.querySelector('input[type="file"]').addEventListener('change', (e) => {
readFilesSequentially(e.target.files);
});
This pattern ensures files are processed in the exact order they appear in the FileList, with each file's completion triggering the next read. It's like a queue at a coffee shop—each customer is served completely before the next one steps up.
Key Takeaway: Sequential file reading uses recursion or iteration with FileReader event handlers to process files one at a time in order, preventing race conditions and maintaining predictable execution flow.