I'm building a form validation and to learn promises I decided to implement asynchronous validation functions using promise pattern:
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() {
//...
})
});
This seems to be working fine, the input is validated as user types (the code is simplified not to be too long, for example timeout after the keyup is missing and so on).
Now I'm wondering how to kill the ajax request if the validation from the previous keyup event is still in progress. Is it somehow possible to detect in which state the promise is and possibly reject the promise from outside?