【问题标题】:Why is not this promise catch fired in my promises array为什么我的 promises 数组中没有触发这个 promise catch
【发布时间】:2021-08-21 19:45:47
【问题描述】:

我学习 React JavaScript 并且有这个 Codesandbox 我不明白为什么没有显示错误

watchProgress 中,catch 没有被触发,但它在 promise 中被触发,所以我做错了

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}`);
        });
    });
}
  1. 使用文件选择器选择文件
  2. 查看err的日志
  3. 当我循环遍历所有日志时,日志显示承诺中的error,但不显示err

更新

我尝试这样的事情,但我得到 TypeError: p.then is not a function

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}`);
    });

【问题讨论】:

    标签: javascript reactjs promise


    【解决方案1】:

    您应该使用Promise.all 而不是使用forEach,并且在promise 解决之后,您可以循环它。

    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}`);
       });
    

    【讨论】:

    • 谢谢,但我还需要做进度条 setProgressValue(math);并处理捕获错误,这就是forEach
    • 你不能用 foreach 来做,因为它是异步的,会导致不需要的行为。
    • 很好,我不知道,但err 没有被解雇,我怎么能抓住它
    • 我用一些测试代码更新了我的问题,但我得到 TypeError: p.then is not a function
    • @Kid - 你可以看看这个stackoverflow.com/questions/30362733/…
    【解决方案2】:

    您应该使用reduce,而不是forEach

    您可以阅读这篇文章:https://css-tricks.com/why-using-reduce-to-sequentially-resolve-promises-works/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多