gpt4 book ai didi

javascript - 为什么catch block 会运行?

转载 作者:行者123 更新时间:2023-11-28 17:13:38 24 4
gpt4 key购买 nike

我有以下函数,它发出 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com