Initially, let's address the poor formatting. I kindly ask for improved readability in the future.
We can definitely tidy this up.
var XMLHttpRequest
= XMLHttpRequest || require('xmlhttprequest').XMLHttpRequest;
// Initiates a request for 4 buoy page responses.
requestAllBuoys(4, function(requests) {
console.log('Results received!');
// Extract the responses, which are gathered in the order they were requested.
responses = requests.map(function(request) {
return request.responseText;
});
// It's up to you to decide how to handle the data on your page!
updateDom(responses);
});
// Sends requests to all buoy URLs, invoking the specified callback once
// all requests have been completed with an array of XML requests.
function requestAllBuoys (n, cb) {
var latch = makeLatch(n, cb);
makeBuoyURLTo(n).map(function (url, i) {
startXMLRequest('GET', url, latch.bind(undefined, i));
});
}
// Generates a latch function, which will trigger the provided callback
// after being called n times.
function makeLatch (n, cb) {
var remaining = n,
results = [],
countDown;
countDown = function (i, result) {
results[i] = result;
if (--remaining == 0 && typeof cb == 'function') {
cb(results);
}
}
return countDown;
}
// Creates an array of buoy URLs from 1 to n.
function makeBuoyURLTo (n) {
var i, buoyUrls = [];
for (i = 1; i <= n; i++) {
buoyUrls.push('getBuoys.php?q=' + i);
}
return buoyUrls;
}
// Builds and initiates an XML request, with the specified method and URL.
// The optional callback will be executed upon successful completion.
function startXMLRequest (method, url, cb) {
var xmlRequest = createXMLRequest();
xmlRequest.onreadystatechange = function () {
if (isXMLFinished(xmlRequest)) {
if (cb && typeof cb == 'function') {
cb(xmlRequest, method, url);
}
}
}
xmlRequest.open(method, url, true);
xmlRequest.send();
return xmlRequest;
}
// Initiates an XML request using native HTML5 or MS ActiveX, depending on availability.
function createXMLRequest () {
var xmlRequest;
if (XMLHttpRequest) {
xmlRequest = new XMLHttpRequest();
} else {
xmlRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
return xmlRequest;
}
// Checks if the XML request has finished with a status of 200 (OK).
function isXMLFinished (xmlRequest) {
return (xmlRequest.readyState == 4) && (xmlRequest.status == 200);
}
Although longer, this approach enhances clarity and the time invested in organizing it is time saved debugging.
It also provides access to the final results in a coherent array format. This is the main advantage.
It seems you have a solid grasp of the functionality, except for the DOM update (as it may just overwrite content rapidly).
Refer to this answer for assistance with handling asynchronous callbacks if needed. Maintain clean code for your own benefit.