You could pass a rejected Deferred object:
$.when($.Deferred().reject()).fail(function() {
alert("fail");
});
You can test it in this fiddle.
题
$.when(a1, ...).fail(function() { alert('fail'); });
Is there a value for a1 that would force the deferred object to fail, while not doing any malformed ajax calls within the object ?
解决方案
You could pass a rejected Deferred object:
$.when($.Deferred().reject()).fail(function() {
alert("fail");
});
You can test it in this fiddle.
其他提示
To elaborate on @Frédéric Hamidi, if you have a "async" function which is not already "promisized" then it will often have a success and failure callback.
Then you do something like:
// @returns {promise} a promise
function callAsync(args){
var deferred = $.Deferred();
ApiNotReturningPromise.ajax(args, function success(data) {
deferred.resolve(data);
// if you wish to always fail: o.O
// deferred.reject(data);
}, function fail(error) {
deferred.reject(error);
});
return deferred.promise();
}
Again, you can just fail in both cases here if you wish to, although that seems to make little sense to me, by
But, if it already is a Promise, (and AFAIK promise-like is enough for jQuery) then you can just reuse that promise.