Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abort ajax request in a promise

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?

like image 407
Lukas Kral Avatar asked Sep 10 '15 08:09

Lukas Kral


People also ask

How do I abort ajax request?

Just use ajax.abort(); } //then you make another ajax request $. ajax( //your code here );

Does ajax return a Promise?

ajax returns a promise object, so that we don't have to pass a callback function.

Is ajax same as Promise?

A Promise is an interface for asynchronous operations. An ajax request is a very specific asynchronous operation.

How do I know if ajax request is complete?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.


1 Answers

Promise cancellation is currently under specification, there is no built in way to do this yet (it's coming though). We can implement it 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 on the promise:

var p = validateAjax("..."); // make request
p.abort(); // abort it;
like image 137
Benjamin Gruenbaum Avatar answered Oct 03 '22 15:10

Benjamin Gruenbaum