I have the below jquery deferred logic.
var $qCallA = callA();
var $qCallB = callB();
$.when($qCallA,$qCallB).then(function () {
$("#spinnerDiv").removeClass('spinner show');
});
function callA() {
return $.getJSON("/callA", function (data) {
if (data.status === "success") {
buildTable1(data);
}
});
}
function callB() {
return $.getJSON("/callB", function (data) {
if (data.status === "success") {
buildTable2(data);
}
});
}
I want to return false for $.getJSON call based on response from the backend json. For example , if the data.status == "failure" then I want to return "false" for getJSON . How to achieve this?
Thanks
resolve( [args ] )Returns: Deferred. Description: Resolve a Deferred object and call any doneCallbacks with the given args .
Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.
promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists. If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point.
JQuery does all that and calls success callback if call succeed or error callback if it fails. Jquery also support promise out of box. $. ajax returns a promise object, so that we don't have to pass a callback function.
Sounds like you want to use proper then
callbacks, where you can return a new result value for the promise:
$.when(callA(), callB()).then(function(a, b) {
$("#spinnerDiv").removeClass('spinner show');
if (a && b) …
});
function callA() {
return $.getJSON("/callA").then(function(data) {
if (data.status === "success") {
buildTable1(data);
}
return data.status != "failure";
});
}
function callB() {
return $.getJSON("/callB").then(function(data) {
if (data.status === "success") {
buildTable2(data);
}
return data.status != "failure";
});
}
You should provide success callbacks then
for your $.getJSON
and return custom Deffered
for $.when
to handle.
That way you can manually resolve or reject based on data that's in the JSON.
var $qCallA = callA();
var $qCallB = callB();
$.when($qCallA,$qCallB).then(function (s1, s2) {
$("#spinnerDiv").removeClass('spinner show');
}).fail(function() {
//handle failure
});
function callA() {
return $.getJSON("/callA").then(function (data) {
if (data.status === 'failure') {
return $.Deferred().reject("A: no success");
}
return $.Deferred().resolve(data);
});
}
function callB() {
return $.getJSON("/callB").then(function (data) {
if (data.status === 'success') {
return $.Deferred().resolve(data);
}
return $.Deferred().reject("B: no success");
});
}
Similar JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With