JS例1
此代码假定你要放弃其他请求如果任何一个请求失败(通过404或500的响应,或超时),而并不需要评估的数据响应,以确定业务逻辑故障情况。 $。当()
该方法将解决其主人尽快递延因为所有的Deferreds决心,或拒绝只要Deferreds的一个被拒绝延期的主人。
$.when(fireRequest(1), fireRequest(2),fireRequest(3))
.then(myAllSuccessfulFunc, oneFailedFunc);
function myAllSuccesfulFunc(req1,req2,req3){
//everything returned a 200.
alert("these are not the droids you are looking for");
};
function oneFailedFunc(req1,req2,req3){
//* each req looks like [ "not success", statusText, jqXHR ] */
//feel free to check what failed, but I don't know what you need
req1[2].abort();
req2[2].abort();
req3[2].abort();
};
JS例2
你真正需要的响应解析为数据请求成功,看看你应该从后端失败的原因逻辑其他请求。
var stop = 4;
//if you are sure fireRequest(x) returns a good promise object, do this:
callNext(fireRequest(1),1);
function callNext(promise, currentIndex){
promise.done(function(ajaxArgs){
var jqXHR = ajaxArgs[2];
//replace this with some logic check that makes sense to your app
if(/error/.test(jqXHR.responseText)){
//do something
}else if(currentIndex
callNext(fireRequest(currentIndex+1),currentIndex+1);
}).fail(function(ajaxArgs){
//server returned a 404, or a 500, or something not a success.
});
};