javascript - 为什么catch block 会运行?

标签 javascript ajax asynchronous promise

我有以下函数,它发出 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 block 。为什么要这样运行? then() 是否要运行或 catch() 是否要运行,这不是取决于函数(在本例中为 getSegements)吗?

最佳答案

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

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

关于javascript - 为什么catch block 会运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53942985/

相关文章:

javascript - 使用 Jquery 设置最小高度以避免移动问题

javascript - 提交表单时 AJAX Jquery 验证不起作用

javascript - 如何从异步调用返回响应?

android - PageAsyncTask endHandler 更新调用页面

javascript - 对数组中每个对象进行多个异步操作产生意外结果

javascript - 使用 Ajax 调用从函数返回值

javascript - AngularJS rootScope 在 Controller 中未定义

javascript - Angular 在 http 请求后不更新我的对象

Django >= 3.1 和 is_ajax

javascript - 如何延迟响应直到 POST 有效负载得到验证