2016-11-29 6 views
12

पर आधारित झूठी वापसी मेरे पास नीचे jquery स्थगित तर्क है।jquery स्थगित और सर्वर प्रतिक्रिया

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

मैं बैकएंड जेसन से प्रतिक्रिया के आधार पर $ .getJSON कॉल के लिए झूठी वापसी करना चाहता हूं। उदाहरण के लिए, यदि data.status == "विफलता" तो मैं getJSON के लिए "झूठी" वापस लौटना चाहता हूं। इसे कैसे प्राप्त करें?

धन्यवाद

+2

आप async समारोह से कुछ भी वापस नहीं कर सकते हैं। 'Data.status ==' विफलता 'होने पर आपको वास्तव में क्या करने की ज़रूरत है? –

+0

आप एक एसिंक्रोनस कॉल से वापस नहीं आ सकते .... क्या आप वादे को विफल करना चाहते हैं? – epascarello

+0

हां। मैं वादा को विफल करना चाहता हूं। – JavaUser

उत्तर

4

आप अपने $.getJSON के लिए सफलता कॉलबैक then प्रदान करते हैं और कस्टम लौटना चाहिए Deffered$.when को संभालने के लिए।

इस तरह आप जेएसओएन में मौजूद डेटा के आधार पर मैन्युअल रूप से हल या अस्वीकार कर सकते हैं।

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

8

लगता है कि आपने उचित then कॉलबैक, जहाँ आप वादा के लिए एक नया परिणाम मूल्य लौट सकते हैं का उपयोग करना चाहते:

$.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"; 
    }); 
} 
संबंधित मुद्दे