promise with FileReader does not give desired deferred result - javascript

After using an file input element I would like upload selected files subsequently. Reading the files with FileReader is asynchronous so I tried to defer the upload function call with a promise. It does not work however as the vm.upload() gets called when vm.files array is 'not yet filled'. There is no error from the promise by the way.
Why does the promise not 'wait/ defer'? It might be since I should make a promise closer to the async code (in the map method), but I am not sure why?
let filesPromise = inputFiles => {
return new Promise((resolve, reject) => {
inputFiles.filter(file => !this.queue.some(f => file.name === f.name))
.map(file => {
file.__size = humanStorageSize(file.size)
if (this.noThumbnails || !file.type.startsWith('image')) {
this.queue.push(file)
}
else {
const reader = new FileReader()
reader.onload = (e) => {
let img = new Image()
img.src = e.target.result
file.__img = img
this.queue.push(file)
this.__computeTotalSize()
}
reader.readAsDataURL(file)
}
return file
})
resolve(inputFiles)
reject(new Error('An error occurred in filesPromise'))
})
}
filesPromise(eventFiles)
.then(eventFiles => vm.files.concat(eventFiles))
.then(() => vm.upload())
.catch(error => console.log('An error occurred: ', error))

As #baao commented, a map method containing async code (FileReader event) will just continue and not wait. To solve this the FileReader needs to be put into a Promise and to keep using map with Promises one should build an array consisting of Promise-elements. On this array you can subsequently run Promise.all. This code works:
let filesReady = [] // List of image load promises
files = inputFiles.filter(file => !this.queue.some(f => file.name === f.name))
.map(file => {
initFile(file)
file.__size = humanStorageSize(file.size)
file.__timestamp = new Date().getTime()
if (this.noThumbnails || !file.type.startsWith('image')) {
this.queue.push(file)
}
else {
const reader = new FileReader()
let p = new Promise((resolve, reject) => {
reader.onload = (e) => {
let img = new Image()
img.src = e.target.result
file.__img = img
this.queue.push(file)
this.__computeTotalSize()
resolve(true)
}
reader.onerror = (e) => {
reject(e)
}
})
reader.readAsDataURL(file)
filesReady.push(p)
}
return file
})
if (files.length > 0) {
vm.files = vm.files.concat(files)
Promise.all(filesReady)
.then(() => vm.upload())
.catch(error => console.log('An error occurred: ', error))
}

Related

Problem with async/await with FileReader in JavaScript

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.
I'd recommend to "promisify" the Reader thing and then use Promise.all until all the files are uploaded.
uploadDocuments = async (event, files) => {
const filePromises = files.map((file) => {
// Return a promise per file
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async () => {
try {
const response = await this.submitFile(
reader.result,
file.name,
fileType
);
// Resolve the promise with the response value
resolve(response);
} catch (err) {
reject(err);
}
};
reader.onerror = (error) => {
reject(error);
};
reader.readAsDataURL(file);
});
});
// Wait for all promises to be resolved
const fileInfos = await Promise.all(filePromises);
console.log('COMPLETED');
// Profit
return fileInfos;
};
Try this.
Add await before the reader.onload it will hold until then or catch block execute successfully
async uploadDocuments(event) {
for (let file of files) {
let fileName = file.name;
let fileContent;
let reader = new FileReader();
await 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));
}```

Check when all images are done uploading?

I have an array of objects. In each object there are an array of files..
Im looping through all files and uploading them one by one, which works as expected.. However, i want to show a "success" modal when all files from each object are done uploading..
Im struggling a bit here... The code I have so far:
Im thinking im doing something wrong when I do the check on the:
if (allFiles.length === filesToQuestions.length) {
triggerUploadFiles() {
let allFiles = [];
let filesToQuestions = this.filesToQuestions;
filesToQuestions.forEach((item) => {
let files = item.images;
let payload = {
instanceId: item.instanceId,
answerId: item.answerId,
path: item.path,
fileType: item.fileType,
optionId: item.optionId
};
if (files.length > 0) {
files.map(async(file) => {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = async(e) => {
// Make a fileInfo object for storing later
let fileInfo = {
questionId: this.questionId,
name: file.name,
type: file.type,
data: e.target.result,
file: file
};
fileInfo.type.includes('video') ? fileInfo.type = 'video' : fileInfo.type = 'image';
if (payload.instanceId && payload.path) {
const {response} = await uploadFileToCloudinary(fileInfo.data, payload);
try {
this.$store.dispatch('surveys/submitFilesToSurvey', {
instanceId: payload.instanceId,
answerId: payload.answerId,
fileName: response.public_id,
type: fileInfo.type,
optionId: payload.optionId
}).then((response) => {
console.log('file submitted', response);
allFiles.push(fileInfo);
});
} catch (e) {
console.log('could not upload file');
}
}
// If all files have been proceed
if (allFiles.length === filesToQuestions.length) {
const delayForCompletedStatus = 2000;
deletePendingSurveyByID(this.tempSurveyId);
setTimeout(() => {
this.isUploadingFiles = false;
this.$store.dispatch('modals/toggleModal', 'showModalSurveyCreated');
}, delayForCompletedStatus);
}
};
});
}
});
}
You can use Promise.all() to check if all asynchronous events are finished.
The Promise.all() method returns a single Promise that fulfills when all of the promises passed as an iterable have been fulfilled or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.
Promise.all(files.map((file) => {
return new Promise((resolve, reject) => {
...
reader.onload = e => {
// upload file
...
resolve();
}
...
});
})
.then() {
// all asynchronous events are finished!
}
FYI, I added a simple example of using Promise.all.
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('first'), 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('second'), 2000);
});
const promiseList = [promise1, promise2];
Promise.all(promiseList).then(function(values) {
console.log(values);
});

Lag by taking an instance of an array using es6

I got an empty array while I'm logging for an instance of an array!
onSelectMultipleImage = (event): Promise<any> => {
return new Promise(resolve => {
const files = <File[]>event.target.files;
let file: File;
let counter = -1;
const response = [];
while (file = files[++counter]) {
const reader: FileReader = new FileReader();
reader.onload = ((f) => {
return () => {
response.push({
file: f,
base64: reader.result
})
}
})(file);
reader.readAsDataURL(file);
console.log(counter);
if(counter == files.length -1) {
console.log('inside the while');
resolve(response);
}
}
});
};
onImagesSelect = async (event: Event) => {
this.newImages = await this.helper.onSelectMultipleImage(event) || [];
console.log(this.newImages, "Original"); // [file: File, base64: "base 64 long string..."]
console.log([...this.newImages],"instance"); // [] empty array
setTimeout(() => {console.log([...this.newImages, 'instance'])}, 2000); // [file: File, base64: "base 64 long string..."]
}
So why I'm getting the presented result? It's something causing by the base64 presented inside the array? if yes what is the solution?
It doesn't wait reader.onload to be completed. So resolve(response) is called before response.push.
You can create a promise to read one file and return them with Promise.all like following code.
readFile = (file: File): Promise<any> => {
return new Promise(resolve => {
const reader: FileReader = new FileReader();
reader.onload = (f) => {
resolve({
file: f,
base64: reader.result
});
};
reader.readAsDataURL(file);
})
}
onSelectMultipleImage = (event): Promise<any> => {
const files = <File[]>event.target.files;
return Promise.all(files.map(file => readFile(file)));
};

Mapping objects, and using state, and passing value through a function in setState

I have a react application, where i want to set the state equal to an array of objects, that has been passed through a function.
I have two variables, and is the file extension, and one is the raw data base64 encoded.
this.setState({
result: fileItems.map(fileItem => ({
"file": this.findFileTypeHandler(fileItem.file.name),
"data": this.getBase64(fileItem.file)
}))
});
}}>
as of right now i just return the value within the two functions, but the issue occurs, when the functions are not asynchronous.
findFileTypeHandler = file =>{
return file.split('.').pop();
}
getBase64 = file => {
//find en måde at gøre den asynkron
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result)
this.setState({base64: reader.result})
return reader.result;
};
reader.onerror = function (error) {
console.log('error is ', error)
};
}
the best case scenario, would be to setState, and then assign the value for each map iteration, but how can i pass the data through the functions, and set the state respectivly?
How about use Promise.all to wait all files to be read, then setState the results.
Promise.all(
fileItems.map(fileItem => new Promise((resolve, reject) => {
//find en måde at gøre den asynkron
var reader = new FileReader();
reader.readAsDataURL(fileItem.file);
reader.onload = () => {
resolve({
file: this.findFileTypeHandler(fileItem.file.name),
data: {
base64: reader.result
}
});
};
reader.onerror = (error) => reject(error);
}))
)
.then((results) => {
this.setState({
result: results
});
})
.catch((error) => console.log(error));

JavaScript Promise with FileReader

I'm trying to return a split array when a user specifies a text file in an input box using promises, but the console.log keeps returning undefined, despite resolve actually finding the data.
I know im using the promise wrong but i just can't figure it out, any help would be very appreciated
class TextReader {
readFile (event) {
let file = event.target.files[0]
var promise = Promise.resolve()
pFileReader(file)
promise.then(function (result) {
console.log(result)
})
function pFileReader (file) {
return new Promise((resolve, reject) => {
var reader = new FileReader()
reader.onload = function found () {
resolve(reader.result)
}
reader.readAsText(file)
})
}
}
}
This is the code in my html
<input type='file' accept='text/plain' id="file" onchange='ValidateInput(event)'/>
function ValidateInput (event) {
let myTextReader = new TextReader()
let output = myTextReader.readFile(event)
}
A promise is returned by pFileReader and you need to resolve the returned Promise and not a new Promise
class TextReader {
readFile (event) {
let file = event.target.files[0]
var promise = pFileReader(file)
promise.then(function (result) {
console.log(result)
})
function pFileReader (file) {
return new Promise((resolve, reject) => {
var reader = new FileReader()
reader.onload = function found () {
resolve(reader.result)
}
reader.readAsText(file)
})
}
}
}

Categories