[英]Promise inside Array.map or loop alternative?
我想知道您將如何解決以下問題。 我有一個接受多個文件的上載組件。 因此, onDrop
給我accepted
和rejected
文件(基於擴展名和大小)。
從那些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具有可選的第二個參數。 catch
和then
和then
與2個參數之間的區別非常細微:如果checkDimensions
決定拒絕文件,仍然將執行acceptedFiles.push(file)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.