在array.map或循环替代方案中承诺



我想知道您将如何解决以下问题。我有一个接受多个文件的上传组件。因此,onDrop给我acceptedrejected文件(基于扩展和大小(。

从这些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具有可选的第二个参数。catchthen相对于then的差异有2个参数:如果checkDimensions决定拒绝文件,则acceptedFiles.push(file)仍将执行。

最新更新