I am struggling a bit with asynchronous operations and Promises (a quite new concept to me) using FileReader. I have found a very interesting thread about it there, but can't make my script to work despite this great content.
I have a file input accepting multiple files, I want to read those files and push their content into an array. But it seems I am not quite understanding well how a promise works because I still get an empty array at the end.
const inputElement = document.getElementById("trackfiles");
inputElement.addEventListener("change", (e) => {
const selectedFiles = inputElement.files;
let p = Promise.resolve();
for (const file of selectedFiles) {
p = p.then(() =>
readAsData(file).then((content) => {
files_content.push(content);
}),
);
}
console.log(files_content);
});
function readAsData(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = reject;
});
}
When I select files, I get an empty array:
Thank you for your help
