I'm using FileReader in a Vue.js project, and I have a problem with this code:
async uploadDocuments(files) {
for (let file of files) {
let fileName = file.name;
let fileContent;
let reader = new FileReader();
reader.onload = async () => {
fileContent = reader.result;
await this.submitFile(fileContent, fileName, fileType)
.then(/* THEN block */)
.catch(/* CATCH block */);
};
reader.onerror = (error) => { console.warn(error); };
reader.readAsDataURL(file);
}
console.log("COMPLETED");
}
async submitFile(fileContent, fileName, fileType) {
// this function should handle the file upload and currently contains a timeout
await new Promise((resolve) => setTimeout(resolve, 3000));
}
This is the desired execution order (example with two files):
- (wait 3s)
- THEN block (file 1)
- (wait 3s)
- THEN block (file 2)
- COMPLETED
But this is the actual execution order:
- COMPLETED
- (wait 3s)
- THEN block
- THEN block
The "THEN block" is correctly executed after the timeout, but the execution of the code in the for loop continues without waiting the execution of the onload function.
How can I make the reader asynchronous? I tried many solutions (such as wrapping the for loop in a promise and putting the resolve() function inside .then()) but none of them works.
application/multipart-formdata