0

我在 Web 编程方面相对较新,所以这对某些人来说可能很明显,但对我来说不是。异步请求的请求/响应对如何匹配?在极端情况下,我可能有一个异步 jQuery 请求,它调用使用 node.js 并且也是异步的服务器。如果我进行大量此类调用,请求/响应似乎会混淆。有哪些设施可以确保它们不会混淆?

4

1 回答 1

0

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.

于 2012-12-14T23:06:30.520 回答