【问题标题】:Why does catch block run? [duplicate]为什么 catch 块运行? [复制]
【发布时间】:2019-05-25 08:40:31
【问题描述】:

我有以下函数,它发出 ajax 请求或从 API 获取数据。

function getSegements(url) {
    return new Promise((resolve, reject) => {
        request = new XMLHttpRequest();
        request.open('GET', url);
        request.setRequestHeader('Content-Type', 'application/json');

        // request.onload = () => resolve(request.response);
        // request.onerror = () => reject(request.status);

        request.onreadystatechange = function() {

            if (request.readyState === 4)
            { 
                if (request.status === 200)
                {
                    data = JSON.parse(request.response);
                    console.log(data.segements);
                    resolve(data); 
                }
                else
                {
                    reject({status: request.status});
                }
            }
        };
        request.send();
    });
}

调用函数:

getSegements(url).then((data) => {
    //console.log(data);
    //data = JSON.parse(data);
    theWheel = new Winwheel({
        'outerRadius'     : 212,
        'textFontSize'    : 16,
        'textOrientation' : 'horizontal',
        'textAlignment'   : 'outer',
        'numSegments'     : data.no,
        'segments'        : data.segements,
        'animation' :           // Specify the animation to use.
        {
            'type'     : 'spinToStop',
            'duration' : 5,     // Duration in seconds.
            'spins'    : 3,     // Default number of complete spins.
            'callbackFinished' : alertPrize
        }
    });
    theWheel.animation.spins = 9;
    wheelSpinning = false;
})
.catch((err)=>{
    console.log(err);
    alert('Request failed.  Returned status of ' + err.status);
});

当 WinWheel 的参数出现故障时,它会运行 catch 块。为什么会这样跑?如果 then() 将要运行或 catch(),它不取决于函数(在本例中为 getSegements)吗? p>

【问题讨论】:

    标签: javascript ajax asynchronous promise


    【解决方案1】:

    then() 也返回一个 Promise,并且未捕获的异常通过调用链传播,直到找到 catch(),因此 catch() 运行调用链中捕获的任何异常

    new Promise((res, rej) => {
      res()
    }).then(() => {
      throw "in then"
    }).catch(e => console.log(e))

    【讨论】:

    • KITACE,如何阻止它传播到特定的 catch()?如果函数拒绝,我只想使用那个 catch 块?
    • @RafayHassan 您要么在函数中捕获异常,要么按照 Jonases 的说明进行操作
    【解决方案2】:

    实际上.then 有两个参数,一个是在一切正常时调用的函数,另一个是在前一个链中发生错误时调用的函数。在你的情况下,你可以写:

     getSegments(url).then(
       data => { new Whinweel() },
       error => console.log(error)
     );
    

    现在使用.catch(handler) 实际上与.then(null, handler) 相同,如前所述,如果前一个链(包括前一个“then”处理程序)中出现错误,则会调用错误处理程序。

    【讨论】:

    • @JuanMendes,你们两个能详细说明一下吗?
    • @rafay 不,因为胡安没有仔细阅读我的答案:)
    • 这就是我删除评论的原因 :) 但问题已关闭,因为您提到的模式令人困惑,除非您小心,否则可能会错过这种情况。您的示例会错过由new Whinweel 引起的错误,我知道这是 OP 想要的,但似乎是个坏主意
    • 我的意思是它们不相等。看到这个被否决的答案stackoverflow.com/a/53348246/227299
    • @juan 是的,.then(a).catch(b) 等于 then(a).then(undefined, b) 正如答案所说,它可能被否决了,因为它错过了那个问题的重点
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2012-10-20
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多