我在组件中使用 async
方法来上传文件。像这样:
//component
uploadPhotos = async (event: Event) => {
const upload = await this.uploadService.uploadPhotos(event, this.files, this.urls);
}
UploadService
在调用上传后返回一个包含更新文件和路径文件的 promise
。对于到达 resolve()
且没有任何挫折的 promise
,该服务正在按预期工作。但是,如果 reject()
被调用,代码将继续执行,直到到达 reader.onload()
内的 resolve()
。
// 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();
}
}
}
});
}
如果在 resolve()
之前达到 reject()
,是否有办法避免 reader.onload()
阻塞?
最佳答案
是的,reject()
和 resolve()
是普通(回调)函数调用。它们与控制流无关,它们不会停止您的功能。为此使用 return
或 if
/else
。
此外,您的 new Promise
中还有一个循环。如果一个文件阅读器发生错误,它不会影响其他文件阅读器。我建议改为在最内层进行 promisification。然后写
readFile(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = (error: any) => reject(error);
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(file);
});
}
// service
async uploadPhotos(event: Event, oldFiles: File[], oldUrls: string[]): Promise<{files: File[], urls: string[]}> {
try {
const files = (event.target as HTMLInputElement).files;
if ((files.length + oldFiles.length) > 5) {
throw new Error('Número máximo de fotos permitidos é 5.');
}
const newFiles = Array.from(files).filter(newFile =>
!oldFiles.some(oldFile => oldFile.name === newFile.name)
);
if (!newFiles.every(file => file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg')) {
throw new Error('Formato inválido. Somente imagens do formato Png, Jpeg e Jpg são permitidos.');
}
const newUrls = await Promise.all(newFiles.map(file =>
this.readFile(file).catch(error => {
throw new Error(`Erro ao carregar a imagem: ${error}`);
})
));
return {
files: oldFiles.concat(newFiles),
urls: oldUrls.concat(newUrls)
};
} catch(err) {
this.alertService.error(err.message);
throw new Error("something went wrong during file upload");
}
}
关于javascript - Angular - 异步方法不返回被拒绝的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52941598/