Abort ajax request in a promise

 ̄綄美尐妖づ 提交于 2019-12-05 04:30:09

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!