Abort ajax request in promise

I am creating form validation and recognizing promises. I decided to implement asynchronous validation functions using the promise template:

var validateAjax = function(value) { return new Promise(function(resolve, reject) { $.ajax('data.json', {data: {value: value}}).success(function(data, status, xhr) { if (data.valid) { resolve(xhr) } else { reject(data.message) } }).error(function(xhr, textStatus) { reject(textStatus) }) }) } //... var validators = [validateAjax]; $('body').delegate('.validate', 'keyup', function() { var value = $('#the-input').val(); var results = validators.map(function(validator) { return validator(input) }); var allResolved = Promise.all(results).then(function() { //... }).catch(function() { //... }) }); 

It seems that this works fine, the input is checked as user types (the code is simplified so as not to be too long, for example, a timeout after a key is missing, etc.).

Now I am wondering how to kill an ajax request if the verification from the previous keyup event is still ongoing. Is it possible to somehow determine in what state the promise is and, perhaps, to reject the promise from the outside?

+5
source share
1 answer

The promise of cancellation is currently under the spec, there is no built-in way to do it yet (it comes, though). We can implement this ourselves:

 var validateAjax = function(value) { // remove explicit construction: http://stackoverflow.com/questions/23803743 var xhr = $.ajax('data.json', {data: {value: value}}); var promise = Promise.resolve(xhr).then(function(data){ if(!data.isValid) throw new Error(data.message); // throw errors return data; }); promise.abort = function(){ xhr.abort(); }); return promise; } 

Now we can kill the validateAjax calls by calling abort as promised:

 var p = validateAjax("..."); // make request p.abort(); // abort it; 
+8
source

All Articles