2017-06-03 86 views
0

我想知道如何解決以下問題。我有一個接受多個文件的上傳組件。所以onDrop給我acceptedrejected文件(基於擴展名和大小)。Array.map或循環替代內的承諾?

從那些accepted我需要弄清楚他們是否有正確的尺寸,我想使用browser-image-size package

這個包返回一個承諾,但正如你可以在下面看到的,我需要在提供的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']))

回答

1

您的控制檯日誌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後跟thenthen之間的差異與2個參數是微妙的:如果checkDimensions決定拒絕一個文件,acceptedFiles.push(file)仍將被執行。

+0

謝謝!我不知道在執行'.catch()'和'.then()'或'.then(成功,錯誤)'的行爲上存在實際差異。我的看法非常混亂。任何可以在'.catch()'語句之後停止'.then()'方法的方法? – NealVDV

+0

在then/catch中返回Promise.reject()'不會在後面執行。如果使用藍鳥,你可以使用[反射](http://bluebirdjs.com/docs/api/reflect.html) – Laoujin