javascript - $.when(ajax1, ajax2, ajax3).always(ajax1,ajax2,ajax3) fires before the 3 requests are done -
i have 3 different services ask data. if 3 successfull, can load widget allright. if service1 and/or service2 down or respond error, can still load widget limited features. if service3 responding error, no matter if service1 , 2 work ok, means total failure , need show error message.
so tried this:
var s1=$.ajax(url_service1); var s2=$.ajax(url_service2); var s3=$.ajax(url_service3); $.when(s1,s2,s3).always(s1,s2,s3){ //here code looks services ok or wrong //to decide show , how; }
but $.when().always() code triggers 1 of services responds error. same happens
$when(s1,s2,s3).then( successfunc, failurefunc)
meaning failure callback triggered, due failure of of 3 services, can't check status of other 2.
so maybe have failure service1 , can't check if services2 , 3 ok.
the way 3 services finish, no matter right or wrong found far this:
$(document).ajaxstop(function(){ console.log("finished"); });
but, i'm developing small widget insert in pages. isolated rest of content. don't want widget waiting whole $(document) solve al ajax requests, if there any...
hope makes sense. i'm newbie jquery ajax requests thanks!
this catching errors (on service1 , service2) , recovering them.
promises make async error recovery simple. in promise libs, chain .catch()
. jquery doesn't yet have method (roll-on jquery v3!), it's still simple - chain .then()
, return resolved promise error handler.
here's flow control :
var s1 = $.ajax(url_service1).then(null, catch_); var s2 = $.ajax(url_service2).then(null, catch_); var s3 = $.ajax(url_service3); $.when(s1, s2, s3).then(loadwidget, widgetfailure);
and here sample functions :
function catch_(error) { // return fulfilled promise delivers detectable error code, eg -1. // value do, long can distinguished successful value. return $.when(-1); } function loadwidget(val1, val2, val3) { //exactly write here depends on how widget initialized when val1 and/or val2 missing. // eg ... if(val1 != -1 && val2 === -1) { //load limited widget based on val1 , val3 } else if(val1 === -1 && val2 != -1) { //load limited widget based on val2 , val3 } else if(val1 === -1 && val2 === -1) { //load limited widget based on val3 } else { //load full widget based on val1, val2 , val3 } } function widgetfailure(error) { $("#errormessage").text('sorry, widget failed initialize') // show error message console.log(error); // log error }
note: due way $.ajax()
delivers data, successful val1/val2/val3 arrays each comprising [data, textstatus, jqxhr]. interested in data, val1[0]/val2[0]/val3[0].
thus, should have want :
- total success if 3 services succeed.
- partial success if service1 and/or service2 fails.
- total failure if service3 fails, regardless of outcome of service1/service2.
Comments
Post a Comment