Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Last active October 23, 2018 12:03
Show Gist options
  • Save tobiashm/0a987db2f9ec8e5cdbb3 to your computer and use it in GitHub Desktop.
Save tobiashm/0a987db2f9ec8e5cdbb3 to your computer and use it in GitHub Desktop.
Wrap jQuery AJAX in ES6 Promise
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));
};
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);
@malthejorgensen
Copy link

Also, the reason why you would use this is to be able to use .catch() on a chain of promises, so that you can have a single error handler if any one call in a series of AJAX calls fail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment