I'm using an async method in component for file upload. Like this:
//component
uploadPhotos = async (event: Event) => {
const upload = await this.uploadService.uploadPhotos(event, this.files, this.urls);
}
UploadService returns a promise with the updated files and path files after upload is called. The service is working as expected for a promise that reaches resolve() without any setbacks. However, if reject() is called, the code will keep going until it reaches the resolve() inside reader.onload().
// service
uploadPhotos(event: Event, oldFiles: File[], oldUrls: string[]): Promise<{files: File[], urls: string[]}> {
return new Promise((resolve, reject) => {
const files = (event.target as HTMLInputElement).files;
if ((files.length + oldFiles.length) > 5) {
this.alertService.error('Número máximo de fotos permitidos é 5.');
reject();
// there is an error, so it reaches here first
}
for (let i = 0; i < files.length; i++) {
const exists = oldFiles.findIndex(file => file.name === files[i].name);
if (exists === -1) {
if (files[i].type === 'image/png' || files[i].type === 'image/jpeg') {
oldFiles.push(files[i]);
const reader = new FileReader();
reader.onerror = (error: any) => {
this.alertService.error(`Erro ao carregar a imagem: ${error}`);
reject();
};
reader.readAsDataURL(files[i]);
reader.onload = () => {
// it reaches here after reject()
oldUrls.push(reader.result);
if (i === files.length - 1) { resolve({ files: oldFiles, urls: oldUrls }); }
};
} else {
this.alertService.error('Formato inválido. Somente imagens do formato Png, Jpeg e Jpg são permitidos.');
reject();
}
}
}
});
}
Is there a way to avoid that reader.onload() block if reject() is reached before resolve()?
loadhandler is called even if there's an error, is that it? (sounds a bit odd) If so, there's a solution, but just for clarity's sake, can you confirm that?reject()if (i === files.length - 1) {test is weird (it will only ever trigger onfiles[files.length - 1]regardless of the order in which they actually get processed, I'm doubtful that thePromisealways resolves with allurls?resolveafter last element is added. However if something goes wrong between the process I would like to abort mission.rejectisn't likereturnit doesn't end function execution ... tryreturn reject(...)