Last active
October 23, 2018 12:03
-
-
Save tobiashm/0a987db2f9ec8e5cdbb3 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)); | |
}; | |
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.