簡體   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