node.js回调被多次调用

时间:2011-08-18 20:29:46

标签: node.js callback zeromq

我今天刚开始玩node.js和zeromq绑定,并且看到了一些我不太了解的行为。

这是我的示例代码,它在同一台机器上的端口9000上调用另一个基于ruby的zeromq REP进程:

var zeromq = require("zmq");
var http = require('http');

var counter = 0;

var availabilityResponse = function(counter, data, request, response) {
    var str = data.toString('utf-8');
    console.log(str);
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.write(str);
    response.end();                 
}

var zmqSocket = zeromq.createSocket('request');
zmqSocket.connect("tcp://127.0.0.1:9000");


var server = http.createServer()
server.on('request', function(request, response) {
    counter += 1;
    zmqSocket.send("Hola! - This is call # " + counter);
    zmqSocket.on('message', function(data) {
        availabilityResponse(counter, data, request, response);
    });

});
server.listen(8888);
console.log("Starting HTTP server on port 8888");

我正在使用浏览器点击节点服务器并等待响应。奇怪的是,我在控制台中获得的输出是以一种附加的方式出现的,我不是很喜欢:

Request received: Hola! - This is call # 1 - Now going to sleep for 1.0

Request received: Hola! - This is call # 2 - Now going to sleep for 3.0
Request received: Hola! - This is call # 2 - Now going to sleep for 3.0

Request received: Hola! - This is call # 3 - Now going to sleep for 3.0
Request received: Hola! - This is call # 3 - Now going to sleep for 3.0
Request received: Hola! - This is call # 3 - Now going to sleep for 3.0

Request received: Hola! - This is call # 4 - Now going to sleep for 2.0
Request received: Hola! - This is call # 4 - Now going to sleep for 2.0
Request received: Hola! - This is call # 4 - Now going to sleep for 2.0
Request received: Hola! - This is call # 4 - Now going to sleep for 2.0

我尝试在http请求块之外移动zmqSocket.on()调用,这会删除附加行为,但它也不会包含我需要的请求/响应对象。

本练习的目的是让浏览器等待,直到响应从端口9000上长时间运行的zeromq服务器进程返回(目前只是一个伪造的睡眠响应)。

我很确定我只是误解了这里的回调,但在这种情况下的文档方式上找不到太多。

感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

每次传入请求进入时,您都会重新绑定zmqSocket.on('message',function(data){event。这会导致多个事件绑定,将该代码块移到请求处理程序之外。

答案 1 :(得分:0)

尝试:

server.on('request', function(request, response) {
    counter += 1;
    zmqSocket.send("Hola! - This is call # " + counter);
    zmqSocket.once('message', function(data) {
        availabilityResponse(counter, data, request, response);
    });

});

这样,每次只能为一条消息绑定该函数。