I am relatively new at Web programming so this might be obvious to some but not to me. How are request/response pairs matched up for asynchronous requests? In the extreme I might have an asynchronous jQuery request that makes a call to the server that is using node.js and is also asynchronous. If I make a lot of these type of calls it would appear that the request/response would get mixed up. What facilities are available to make sure they don't get mixed up?
The requests and their responses cannot get mixed up as you would typically provide a callback function into the function that initiates the request to a server. Node keeps the two together.
for example:
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
The http.get function will initiate a request to google and node will store a reference to your callback function (function(res){...}).
Node will then continue executing your current function (any code that comes after http.get) until a point where it no longer has any code to execute.
As soon as google starts sending a response back and node isn't doing anything else, node finds your function and the corresponding response object will be passed to it, ready for you to use it.
Node is single threaded, which means that it cannot do more than 1 thing at a time. That's why it doesn't call your callback function until it is finished executing the current function and google has responded.
Have a look here for more info: http://nodejs.org/api/http.html#http_class_http_clientrequest
PS: you don't have to provide a callback function. However, if you don't, you will never know whether the request was successful or not. So it's good practice to always provide one. At the very least it should log any errors.