繁体   English   中英

在Array.map中承诺还是循环替代?

[英]Promise inside Array.map or loop alternative?

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

从那些accepted我需要弄清楚它们是否具有正确的尺寸,并且我想使用browser-image-size软件包

这个包返回一个promise,但是正如您在下面看到的,我需要在提供的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);
    });
  );
}

then A具有可选的第二个参数。 catchthenthen与2个参数之间的区别非常细微:如果checkDimensions决定拒绝文件,仍然将执行acceptedFiles.push(file)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM