JS示例1
此代码假定您希望在任何一个请求失败(通过 404 或 500 响应,或超时)时中止其他请求,并且不需要评估数据响应以确定业务逻辑故障场景。$.when()
该方法将在所有 Deferred 解析后立即解析其主 Deferred,或者在其中一个 Deferred 被拒绝时拒绝主 Deferred。
$.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 <stop){
callNext(fireRequest(currentIndex+1),currentIndex+1);
}).fail(function(ajaxArgs){
//server returned a 404, or a 500, or something not a success.
});
};