I have a situation where I want to cancel a deferred. The deferred is associated with an ajax call.
Why I am using deferreds
I don't use the normal xhr objects returned by $.ajax. I'm using jsonp, which means I can't use HTTP status codes for error handling and have to embed them in the responses. The codes are then examined and an associated deferred object is marked as resolved or rejected accordingly. I have a custom api function that does this for me.
function api(options) {
var url = settings('api') + options.url;
var deferred = $.Deferred(function(){
this.done(options.success);
this.fail(options.error);
});
$.ajax({
'url': url,
'dataType':'jsonp',
'data': (options.noAuth == true) ? options.data : $.extend(true, getAPICredentials(), options.data)
}).success(function(jsonReturn){
// Success
if(hasStatus(jsonReturn, 'code', 200)) {
deferred.resolveWith(this, [jsonReturn]);
}
// Failure
else {
deferred.rejectWith(this, [jsonReturn]);
}
});
return deferred;
}
Why I want to cancel the deferred
There is an input field that serves as a filter for a list and will automatically update the list half a second after typing ends. Because it is possible for two ajax calls to be outstanding at a time, I need to cancel the previous call to make sure that it doesn't return after the second and show old data.
Solutions I don't like
- I don't want to reject the deferred because that will fire handlers attached with
.fail()
.
- I can't ignore it because it will automatically be marked as resolved or rejected when the ajax returns.
- Deleting the deferred will cause an error when the ajax call returns and tries to mark the deferred as resolved or rejected.
What should I do?
Is there a way to cancel the deferred or remove any attached handlers?
Advice on how to fix my design is welcome, but preference will be given to finding a way to remove handlers or prevent them from firing.
question from:
https://stackoverflow.com/questions/11531184/can-jquery-deferreds-be-cancelled 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…