在承诺中中止ajax请求 [英] Abort ajax request in a promise

查看:104
本文介绍了在承诺中中止ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建表单验证并学习承诺我决定使用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() {
        //...
    })
});

这似乎工作正常,输入验证为用户类型(代码简化为不太长了,例如在keyup丢失后超时等等。)

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).

现在我想知道如果从前一个keyup验证如何杀死ajax请求事件仍在进行中。是否可能以某种方式检测承诺在哪种状态并可能拒绝来自外部的承诺?

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?

推荐答案

目前正在取消承诺规范,没有内置的方法来做到这一点(虽然它即将到来)。我们可以自己实现:

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;
}

现在,我们可以通过调用来终止validateAjax调用承诺中止

Now, we can kill the validateAjax calls by calling abort on the promise:

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

这篇关于在承诺中中止ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆