0

I have the following function which makes an ajax request o fetch data from an 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();
    });
}

calling the function:

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

When there is a fault in WinWheel's parameter it runs the catch block. Why is running like that? Doesn't it depend on the function (in this case getSegements) if then() is going to run or catch()?

Rafay Hassan
  • 740
  • 8
  • 23

2 Answers2

2

then() returns a Promise as well, and uncaught exceptions are propagated through the call chain until catch() is found, and therefore catch() runs for any exception caught in a call chain

new Promise((res, rej) => {
  res()
}).then(() => {
  throw "in then"
}).catch(e => console.log(e))
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
1

Actually .then takes two arguments, one function called when everything is fine and one that gets called when an error occured in the previous chain. In your case you could write:

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

Now using .catch(handler) is actually the same as .then(null, handler), and as stated earlier, the error handler gets called if there was an error in the previous chain, including the previous "then" handler.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • @JuanMendes, can you two elaborate it bit more? – Rafay Hassan Dec 27 '18 at 10:08
  • @rafay no, because Juan did not read my answer carefully :) – Jonas Wilms Dec 27 '18 at 10:13
  • That's why I deleted the comment :) But the question was closed because the pattern you mentioned is confusing and could miss exactly this case unless you're careful. Your example would miss errors caused by `new Whinweel`, I know that is what the OP wanted but seems like a bad idea – Ruan Mendes Dec 27 '18 at 19:57
  • My point is that they are not equivalent. See this downvoted answer https://stackoverflow.com/a/53348246/227299 – Ruan Mendes Dec 27 '18 at 20:06
  • @juan yes, `.then(a).catch(b)` equals `then(a).then(undefined, b)` just as the answer says, it aas probably downvoted because it missed the point of that question – Jonas Wilms Dec 27 '18 at 21:33
  • Yes, I realize that, but I think you would agree that is pretty confusing, and people are likely to write `then(a,b)` and expect it to catch errors in a . – Ruan Mendes Dec 29 '18 at 13:08
  • @juan yes, but the OP wants that behaviour. – Jonas Wilms Dec 29 '18 at 13:11