Skip to content

Instantly share code, notes, and snippets.

@jhorneman
Last active April 14, 2016 12:39
Show Gist options
  • Save jhorneman/0dbdd87ef50a4a41c730fd7ebb39cdfb to your computer and use it in GitHub Desktop.
Save jhorneman/0dbdd87ef50a4a41c730fd7ebb39cdfb to your computer and use it in GitHub Desktop.
Accessing full jQuery error information when using Q
// The Q 'coming from jQuery' wiki page (https://github.com/kriskowal/q/wiki/Coming-from-jQuery) says the following:
//
// "So if you are used to writing code like
// $.ajax(...).then(function (data, status, xhr) {
// console.log(data, status, xhr);
// });
// when transitioning to Q [...] you should assume they only return a single object"
//
// That is all well and good, but doesn't address how to access the multiple parameters jQuery sends, and which
// can be important.
//
// Here is a function which builds a jQuery AJAX promise, then turns it into a Q promise while correctly processing
// jQuery's error information.
//
// It calls a function called interpretAJAXError which takes jQuery's jqXHR, textStatus, errorThrown parameters
// (see http://api.jquery.com/jQuery.ajax/, under 'error') and turns it into a single value. This function can be
// arbitrarily complex, looking at all parameters, custom messages, etc.
function buildAJAXPromise(_options) {
var jQueryPromise = $.ajax(Object.assign({}, {
dataType: 'json',
timeout: 3000,
}, _options));
// Copy of Q's coerce (https://github.com/kriskowal/q/blob/v1/q.js#L1185)
// We intercept the error parameters, collect them, then send them on to Q's deferred.
var deferred = Q.defer();
Q.nextTick(function () {
try {
jQueryPromise.then(
deferred.resolve,
function(jqXHR, textStatus, errorThrown) {
return deferred.reject(interpretAJAXError(jqXHR, textStatus, errorThrown));
},
deferred.notify
);
} catch (exception) {
deferred.reject(exception);
}
});
return deferred.promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment