Why does catch block run?
本问题已经有最佳答案,请猛点这里访问。
我有以下函数,它使ajax请求从API获取数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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(); }); } |
调用函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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)?
1 2 3 4 5 | new Promise((res, rej) => { res() }).then(() => { throw"in then" }).catch(e => console.log(e)) |
实际上
1 2 3 4 | getSegments(url).then( data => { new Whinweel() }, error => console.log(error) ); |
现在使用