With the caveat that I have not tested this code (since I don't have your API handy), I think something like the following would be closer to idiomatic usage of RSVP:
var initialUrl = "http://localhost:3000/api/foo_resources/1/reports/bar";
var headers = {
"Accept": 'application/vnd.xps+json; version=1', // Headers for API access
"X-User-Email": 'example@company.com',
"X-User-Token": '1234abcd',
};
function rsvpAjax(opts){
return new RSVP.promise(function(resolve, reject){
var defaultOpts = {
type: 'GET',
headers: headers,
dataType: 'json',
xhrFields: {
withCredentials: true
}
};
$.ajax($.extend({}, defaultOpts, opts, {
success: function(json) {
resolve(json);
},
error: function(jqXhr, textStatus, errorThrown){
reject({ jqXhr: jqXhr, textStatus: textStatus, errorThrown: errorThrown});
}
}));
});
}
function requestBucket(bucket){
return rsvpAjax({ url: bucketUrl }).then(bucketResponseProcessor(bucket));
}
function bucketResponseProcessor(bucket){
return function(response){
$.merge(bucket.reports, response.reports);
if (response.next) {
bucket.url = response.next;
return requestBucket(bucket);
} else {
return bucket.reports;
}
};
}
rsvpAjax({ url: initialUrl }).then(function(response) {
return RSVP.all(response.buckets.map(function(bucketUrl){
var bucket = { url: bucketUrl, reports: [] };
return requestBucket(bucket).then(processBucketResponse);
}));
}).then(function(reports) {
console.dir(data);
}).catch(function(error) {
console.dir(error);
});