我编写了以下等待响应的代码。如果我在5秒后没有得到响应,如何注册超时回调?
var zmqRequest = zmq.socket('req');
zmqRequest.connect('tcp://localhost:8188');
zmqRequest.send(request.params.fileGuid);
console.log('request sent ' + request.params.fileGuid);
zmqRequest.on('message', function(msg){ // report back to the user... });
答案 0 :(得分:1)
我写了一个使用setTimeout
检查超时请求的功能。此示例使用Typescript,但应该很容易转换为vanilla javascript。
import * as zmq from 'zmq';
function sendZMQRequest(params:any, doneCallback:(error:any, results:any) => void):void{
// init zmq socket.
var zmqreq = zmq.socket('req');
var connectAddress = 'tcp://0.0.0.0:8200';
zmqreq.connect(connectAddress);
// uses setTimeout later.
var timeout;
// callback for zmq response.
var requestCallback = (response:Buffer) => {
// clear the timer when a response comes back.
clearTimeout(timeout);
// parse response and add any error checking you might need.
if(response){
var parsedResp = JSON.parse(response.toString('utf8'));
doneCallback(null, parsedResp);
} else {
doneCallback(new Error('Bad Response'), null);
}
};
zmqreq.send(params);
timeout = setTimeout(() => {
zmqreq.close();
zmqreq.removeListener('message', requestCallback);
doneCallback(new Error('Request Timed Out After 3 Seconds'), null);
}, 3000);
zmqreq.on('message', requestCallback);
}