Why does catch block run? [duplicate]












0















This question already has an answer here:




  • When is .then(success, fail) considered an antipattern for promises?

    5 answers




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()?










share|improve this question













marked as duplicate by Bergi javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
15 hours ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




















    0















    This question already has an answer here:




    • When is .then(success, fail) considered an antipattern for promises?

      5 answers




    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()?










    share|improve this question













    marked as duplicate by Bergi javascript
    Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

    StackExchange.ready(function() {
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function() {
    $hover.showInfoMessage('', {
    messageElement: $msg.clone().show(),
    transient: false,
    position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
    dismissable: false,
    relativeToBody: true
    });
    },
    function() {
    StackExchange.helpers.removeMessages();
    }
    );
    });
    });
    15 hours ago


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















      0












      0








      0








      This question already has an answer here:




      • When is .then(success, fail) considered an antipattern for promises?

        5 answers




      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()?










      share|improve this question














      This question already has an answer here:




      • When is .then(success, fail) considered an antipattern for promises?

        5 answers




      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()?





      This question already has an answer here:




      • When is .then(success, fail) considered an antipattern for promises?

        5 answers








      javascript ajax asynchronous promise






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 17 hours ago









      Rafay Hassan

      6910




      6910




      marked as duplicate by Bergi javascript
      Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      15 hours ago


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






      marked as duplicate by Bergi javascript
      Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      15 hours ago


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


























          2 Answers
          2






          active

          oldest

          votes


















          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.






          share|improve this answer





















          • @JuanMendes, can you two elaborate it bit more?
            – Rafay Hassan
            17 hours ago










          • @rafay no, because Juan did not read my answer carefully :)
            – Jonas Wilms
            16 hours ago










          • 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
            – Juan Mendes
            7 hours ago












          • My point is that they are not equivalent. See this downvoted answer stackoverflow.com/a/53348246/227299
            – Juan Mendes
            7 hours ago










          • @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
            5 hours ago



















          1














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








          share|improve this answer























          • KITACE, How can I stop it from propagating to that specific catch()? I only want to use that catch block if function rejects?
            – Rafay Hassan
            17 hours ago










          • @RafayHassan you either catch an exception in a function or follow Jonases' instructions
            – NEGR KITAEC
            15 hours ago


















          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          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.






          share|improve this answer





















          • @JuanMendes, can you two elaborate it bit more?
            – Rafay Hassan
            17 hours ago










          • @rafay no, because Juan did not read my answer carefully :)
            – Jonas Wilms
            16 hours ago










          • 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
            – Juan Mendes
            7 hours ago












          • My point is that they are not equivalent. See this downvoted answer stackoverflow.com/a/53348246/227299
            – Juan Mendes
            7 hours ago










          • @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
            5 hours ago
















          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.






          share|improve this answer





















          • @JuanMendes, can you two elaborate it bit more?
            – Rafay Hassan
            17 hours ago










          • @rafay no, because Juan did not read my answer carefully :)
            – Jonas Wilms
            16 hours ago










          • 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
            – Juan Mendes
            7 hours ago












          • My point is that they are not equivalent. See this downvoted answer stackoverflow.com/a/53348246/227299
            – Juan Mendes
            7 hours ago










          • @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
            5 hours ago














          1












          1








          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.






          share|improve this answer












          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.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 17 hours ago









          Jonas Wilms

          54.8k42749




          54.8k42749












          • @JuanMendes, can you two elaborate it bit more?
            – Rafay Hassan
            17 hours ago










          • @rafay no, because Juan did not read my answer carefully :)
            – Jonas Wilms
            16 hours ago










          • 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
            – Juan Mendes
            7 hours ago












          • My point is that they are not equivalent. See this downvoted answer stackoverflow.com/a/53348246/227299
            – Juan Mendes
            7 hours ago










          • @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
            5 hours ago


















          • @JuanMendes, can you two elaborate it bit more?
            – Rafay Hassan
            17 hours ago










          • @rafay no, because Juan did not read my answer carefully :)
            – Jonas Wilms
            16 hours ago










          • 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
            – Juan Mendes
            7 hours ago












          • My point is that they are not equivalent. See this downvoted answer stackoverflow.com/a/53348246/227299
            – Juan Mendes
            7 hours ago










          • @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
            5 hours ago
















          @JuanMendes, can you two elaborate it bit more?
          – Rafay Hassan
          17 hours ago




          @JuanMendes, can you two elaborate it bit more?
          – Rafay Hassan
          17 hours ago












          @rafay no, because Juan did not read my answer carefully :)
          – Jonas Wilms
          16 hours ago




          @rafay no, because Juan did not read my answer carefully :)
          – Jonas Wilms
          16 hours ago












          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
          – Juan Mendes
          7 hours ago






          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
          – Juan Mendes
          7 hours ago














          My point is that they are not equivalent. See this downvoted answer stackoverflow.com/a/53348246/227299
          – Juan Mendes
          7 hours ago




          My point is that they are not equivalent. See this downvoted answer stackoverflow.com/a/53348246/227299
          – Juan Mendes
          7 hours ago












          @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
          5 hours ago




          @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
          5 hours ago













          1














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








          share|improve this answer























          • KITACE, How can I stop it from propagating to that specific catch()? I only want to use that catch block if function rejects?
            – Rafay Hassan
            17 hours ago










          • @RafayHassan you either catch an exception in a function or follow Jonases' instructions
            – NEGR KITAEC
            15 hours ago
















          1














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








          share|improve this answer























          • KITACE, How can I stop it from propagating to that specific catch()? I only want to use that catch block if function rejects?
            – Rafay Hassan
            17 hours ago










          • @RafayHassan you either catch an exception in a function or follow Jonases' instructions
            – NEGR KITAEC
            15 hours ago














          1












          1








          1






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








          share|improve this answer














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








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





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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 17 hours ago









          Juan Mendes

          67.4k20112157




          67.4k20112157










          answered 17 hours ago









          NEGR KITAEC

          356




          356












          • KITACE, How can I stop it from propagating to that specific catch()? I only want to use that catch block if function rejects?
            – Rafay Hassan
            17 hours ago










          • @RafayHassan you either catch an exception in a function or follow Jonases' instructions
            – NEGR KITAEC
            15 hours ago


















          • KITACE, How can I stop it from propagating to that specific catch()? I only want to use that catch block if function rejects?
            – Rafay Hassan
            17 hours ago










          • @RafayHassan you either catch an exception in a function or follow Jonases' instructions
            – NEGR KITAEC
            15 hours ago
















          KITACE, How can I stop it from propagating to that specific catch()? I only want to use that catch block if function rejects?
          – Rafay Hassan
          17 hours ago




          KITACE, How can I stop it from propagating to that specific catch()? I only want to use that catch block if function rejects?
          – Rafay Hassan
          17 hours ago












          @RafayHassan you either catch an exception in a function or follow Jonases' instructions
          – NEGR KITAEC
          15 hours ago




          @RafayHassan you either catch an exception in a function or follow Jonases' instructions
          – NEGR KITAEC
          15 hours ago



          Popular posts from this blog

          Monofisismo

          Angular Downloading a file using contenturl with Basic Authentication

          Olmecas