我学习了React JavaScript,有了这个Codesandbox,我不明白为什么错误没有显示
在watchProgress
中,catch
没有被激发,但它在承诺中被激发了,所以我做了一些错误的
function watchProgress(promArray) {
let progress = 0;
promArray.forEach(p => {
p.then(result => {
progress += 1;
const percentCorrect = (progress / promArray.length) * 100;
const math = Math.floor(percentCorrect);
setProgressValue(math);
console.log(`name ${result.name}`);
}).catch(err => {
console.log(`err ${err}`);
});
});
}
- 使用文件选择器选择文件
- 查看
err
的日志 - 日志显示promise中的
error
,但当我循环所有内容时不显示err
更新
我尝试了这样的方法,但我得到了TypeError:p.然后不是的函数
Promise.all(promArray)
.then(arr => {
arr.forEach(p => {
p.then(result => {
progress += 1;
const percentCorrect = (progress / promArray.length) * 100;
const math = Math.floor(percentCorrect);
// console.log(`setProgressValue ${math}`);
// console.log(`count ${progress}`);
setProgressValue(math);
console.log(`name ${result.name}`);
}).catch(err => {
console.log(`err ${err}`);
});
});
})
.catch(err => {
console.log(`err ${err}`);
});
您应该使用Promise.all
,而不是使用forEach,在承诺得到解决后,您可以通过循环它。
let progress = 0;
Promise.all(promArray).then((promArray) => {
promArray.forEach(p => {
progress += 1;
const percentCorrect = (progress / promArray.length) * 100;
const math = Math.floor(percentCorrect);
setProgressValue(math);
})
}).catch(err => {
console.log(`err ${err}`);
});
您应该使用reduce
而不是forEach
。
你可以阅读这篇文章:https://css-tricks.com/why-using-reduce-to-sequentially-resolve-promises-works/