我编写了以下等待响应的代码。如果我在 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... });
我写了一个函数,它使用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);
}