12

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

JavaUser
  • 25,542
  • 46
  • 113
  • 139

2 Answers2

8

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";
    });
}
Alexander Ciesielski
  • 10,506
  • 5
  • 45
  • 66
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
5

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

Alexander Ciesielski
  • 10,506
  • 5
  • 45
  • 66
anytimecoder
  • 7,204
  • 2
  • 14
  • 18