I'm new to ajax and javascript, and am a little confused as to why my error is not being caught when my ajax call is asynchronous.
I looked through this question already (Catch statement does not catch thrown error), but I am already calling my function which catches my error inside my success block in Ajax.
My code looks something like this:
var Codecheck = {
SundayCheck : function() {
this.check = function (date, boolean) {
if (boolean) return; //skip check
else{
...logic to check if sunday
if(!Sunday)
throw new Error
}
}
}
checkSunday : function(title) {
$.ajax({
url : url,
type : 'GET',
dataType: 'json',
contentType : 'application/json;charset=UTF-8',
async: false,
success : function(response) {
if (response.content == 'checkSunday') {
new Codecheck.SundayCheck().check(date, true);
}
else {
new Codecheck.SundayCheck().check(date, false);
}
},
error : function(response) {
document.write(response.responseText);
}
});
This works fine, and my error is caught. However, once I remove the async: false, the error is no longer caught. I'm calling my check method, and therefore catching my error inside of the success block in ajax so I'm not really sure what's going on.
The only thing I can think of is whatever calls my checkSunday function, the code that is suppose to run afterwards will run if it's async call whereas if it's a sync call then the code will wait.
However, this still doesn't explain how the error handling that should be caught in the method that's only called upon a successful ajax response is not being called regardless of sync or async.