Reputation: 28168
I am resolve jquery ajax requests using bluebird.js, and it is surprisingly difficult to access the http headers of my request.
Sample Code :
Promise.resolve($.get(...)).then(function(data){
//wtb http headers
});
I am trying to get access to the http headers returned with my response. Doing this on just an ajax request is simple, I assume someone smarter than me has figured this out already for promises.
Upvotes: 0
Views: 950
Reputation: 19288
Why coerce the jqXHR
to some other Promise when, by staying in jQuery, the jqXHR is made available to both success and error handlers as a formal variable?
$.get(...).then(function(data, testStatus, jqXHR) {
var headers = jqXHR.getAllResponseHeaders();
...
}, function(jqXHR, testStatus, errorThrown) {
var headers = jqXHR.getAllResponseHeaders();
...
});
If for whatever reason you still need to coerce the jqXHR, then wrap the whole expression in Promise.resolve(...)
. The jQuery promise returned by .then()
is every bit as coercible as a jqXHR.
Upvotes: 1
Reputation: 141827
One way to solve this, is just to keep a reference to the jqXHR object around, so you can access it later:
var jqXHR = $.get(...);
Promise.resolve( jqXHR ).then( function ( data ) {
var headers = jqXHR.getAllResponseHeaders();
} );
Upvotes: 4
Reputation: 91497
One difference between jQuery promises and bluebird promises (which are Promises/A+ compliant), is that your then
function gets only one parameter. If you want to retain all the information that jQuery gives you, you have to wrap it up in a single object:
Promise.resolve($.get(...).then(function(data, status, xhr) {
return {
data: data,
status: status,
xhr: xhr
};
})).then(function (data) {
// data.data has the response data
// data.xhr contains the jqXHR object
});
Upvotes: 2