我想知道您将如何解决以下问题。我有一个接受多个文件的上传组件。因此,onDrop
给我accepted
和rejected
文件(基于扩展和大小(。
从这些accepted
中,我需要弄清楚它们是否具有正确的尺寸,我想使用browser-image-size
软件包。
此软件包返回承诺,但是如下所示,我需要在提供的accepted
参数中对每个文件进行检查。我尝试了以下操作,但是您可以看到这总是返回一个emty数组和未定义的。
如何解决此问题?
const checkDimensions = (file) => {
return Promise.resolve(file);
}
const handleFiles = (accepted, rejected) => {
const acceptedFiles = [];
const errors = [];
accepted.map(file =>
checkDimensions(file)
.catch((error) => errors.push(error))
.then((file) => acceptedFiles.push(file))
);
// both log empty array
console.log(acceptedFiles);
console.log(errors);
}
// Logs undefined
console.log(handleFiles(['test file']))
在checkDimensions
有机会完成工作之前,您的控制台日志是执行的。
const handleFiles = (accepted, rejected) => {
const acceptedFiles = [];
const errors = [];
accepted.map(file => checkDimensions(file)
.then(file => acceptedFiles.push(file), error => errors.push(error))
.then(() => {
console.log(acceptedFiles);
console.log(errors);
});
);
}
a then
具有可选的第二个参数。catch
与then
相对于then
的差异有2个参数:如果checkDimensions
决定拒绝文件,则acceptedFiles.push(file)
仍将执行。