-
-
Save malthejorgensen/eda53dd4f00c443354fc2a9965d61d0c to your computer and use it in GitHub Desktop.
Wrap jQuery AJAX in ES6 Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function AjaxError(jqXHR, textStatus, errorThrown) { | |
this.name = "AjaxError"; | |
this.message = textStatus; | |
this.jqXHR = jqXHR; | |
this.errorThrown = errorThrown; | |
} | |
AjaxError.prototype = new Error(); | |
AjaxError.prototype.constructor = AjaxError; | |
(function($) { | |
function decorateAsJQuery(promise) { | |
promise.done = function(fn) { | |
return decorateAsJQuery(promise.then(fn)); | |
}; | |
promise.fail = function(fn) { | |
return decorateAsJQuery(promise.then(null, fn)); | |
}; | |
promise.complete = function(fn) { | |
return decorateAsJQuery(promise.then(fn, fn)); | |
}; | |
promise.always = promise.complete; | |
return promise; | |
} | |
var jqAjax = $.ajax; | |
$.ajax = function ajax() { | |
var args = Array.prototype.slice.call(arguments); | |
var jqPromise = jqAjax.apply(this, args); | |
var promise = new Promise(function(resolve, reject) { | |
jqPromise.then(function(data, textStatus, jqXHR) { | |
resolve(data); | |
}, function(jqXHR, textStatus, errorThrown) { | |
reject(new AjaxError(jqXHR, textStatus, errorThrown)); | |
}); | |
}); | |
return decorateAsJQuery(promise); | |
}; | |
})(jQuery); |
Promise chaning is available by default in jQuery, but .catch()
is not: https://jsfiddle.net/x7k0yem9/3/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$(element).load()
fails whenjqXHR.always()
isn't defined. Example: https://jsfiddle.net/30p2ft80/