Cuthbert
Cuthbert

Reputation: 2998

How can I set a timeout for a zmq request in Node.js?

I have written the following code that is waiting for a response. How can register a timeout callback if I don't get a response after 5 seconds?

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... }); 

Upvotes: 1

Views: 1230

Answers (1)

Cuthbert
Cuthbert

Reputation: 2998

I wrote a functon that uses setTimeout to check for timed out requests. This example uses Typescript, but should be easy to translate to 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);
}

Upvotes: 1

Related Questions