So I have the following code:
function ajax1(url) {
return $.ajax({
url: url
});
}
function ajax2(url) {
return $.ajax({
url: url
});
}
function ajax3(url) {
return $.ajax({
url: url
});
}
function ajax4(url) {
return $.ajax({
url: url
});
}
I then run the Ajax calls and access the data returned by each one using $.when
:
$.when(ajax1(url), ajax2(url), ajax3(url), ajax4(url)).done(function(a1, a2, a3, a4){
});
Now, let's say one of the Ajax calls, ajax2
, will return a 404 error.
How can prevent the script from executing and still return something (like false, to be accessed using the a2
variable) even when a 404 error is returned?
Thank you very much in advance.
jQuery 3 Deferreds are Promises A+ compliant. That means you can add a catch()
to the request promise
Whenever you return from a catch()
it resolves the promise and whatever is returned will be passed to the next then()
in the chain
function ajax1(url) {
return $.ajax({
url: url
})
.then(data => data)
.catch(resolveFailure);
}
function resolveFailure(jqXhr) {
// return whatever you want here. I added the status in case that is of interest
// could return `false` or string or whatever
// can also log any issues back to server if needed
return {
error: true,
status: jqXhr.status,
statusText: jqXhr.statusText
};
}
var req = ajax1('https://api.myjson.com/bins/l9ywp'),
req2 = ajax1('https://httpbin.org/FAIL'),
req3 = ajax1('https://api.myjson.com/bins/l9ywp');
// could also replace `$.when with `Promise.all()`
$.when(req, req2, req3).then(function(r1, r2, r3) {
// validate the arguments based on whatever you return in the catch()
console.log('r1', r1);
console.log('r2', r2);// object returned from catch()
console.log('r3', r3);
});
.as-console-wrapper {max-height: 100%!important;top:0}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments