Currently, my component utilizes an async
method for handling file uploads. Here is an example:
//component
uploadPhotos = async (event: Event) => {
const upload = await this.uploadService.uploadPhotos(event, this.files, this.urls);
}
The UploadService
returns a promise
containing the updated files and path files once the upload is completed. Everything works as intended when the promise
successfully reaches resolve()
. However, if reject()
is triggered, the code continues execution until it encounters 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();
}
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 = () => {
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 skip the reader.onload()
block if reject()
is called before resolve()
?