Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Created November 4, 2014 11:51
Show Gist options
  • Select an option

  • Save tobiashm/8d724b4f981c5462c80a to your computer and use it in GitHub Desktop.

Select an option

Save tobiashm/8d724b4f981c5462c80a to your computer and use it in GitHub Desktop.
Wrap jQuery Ajax in real Promise
(function() {
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 wrapAjax(jqPromise) {
return new Promise(function(resolve, reject) {
jqPromise.then(function(data, textStatus, jqXHR) {
resolve(data);
}, function(jqXHR, textStatus, errorThrown) {
reject(new AjaxError(jqXHR, textStatus, errorThrown));
});
});
}
Promise.wrapAjax = wrapAjax;
})();
@tobiashm

tobiashm commented Oct 6, 2015

Copy link
Copy Markdown
Author

If you want access to the metadata on success, just do:

resolve({ data: data, textStatus: textStatus, jqXHR: jqXHR });

and in the consumer code, something like:

request.then((response) => render(response.data));

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