Да, есть более элегантный способ.Основная идея - «не повторяйся».
function doXHR(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(event) {
// XMLHttpRequest.DONE === 4
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
return callback(null, this.responseText);
} else {
return callback({errCode: this.status, errMsg: this.statusText});
}
}
};
xhr.open('GET', url, true);
xhr.send(null);
}
doXHR('http://website-one.com/FIRST.json', function(errFirst, responseFirst) {
if (errFirst) {
throw new Error('Something bad happened : ' + errFirst.errCode + '/' + errFirst.errMsg);
}
return doXHR('http://website-two.com/second.json', function(errSecond, responseSecond) {
if (errSecond) {
throw new Error('Something bad happened : ' + errSecond.errCode + '/' + errSecond.errMsg);
}
return work_with_them(responseFirst, responseSecond);
});
});