0

I am newbie with node.js. I am using Restify with node.js.

I had to send several request to BigCommerce API.

I actually increment the counter for every response, so success and error cases are heldled, only case left out is when i get no reply. For the safer side I wanted to handle time-out issue, ie handle a case when i do not get reply to some of request from the API.

How can i handle request time-out for each of the request that is sent via JsonClient(Restify)?

Thanks.

Chirag B
  • 2,106
  • 2
  • 20
  • 35

1 Answers1

0

It sounds like what you're doing is sending several API requests all at once before you get a response to any particular request (i.e., all in parallel) and that you're doing reference counting on the API responses that you receive to know when you're done.

If that's what you're doing then the most basic version of a timeout for that situation would be something like this (NOTE: I haven't tested this):

var apiTimeout;

function apiTimedOut() {
    console.log("Yikes!");
    apiTimeout = null;
}

function doABunchOfAPICalls() {
        // call 'apiTimedOut' after 1 second (unless gotAllAPIResponses called first).
    apiTimeout = setTimeout(function() {apiTimedOut();}, 1000);   

    ... do all your API calls here...
}

    // called from wherever you are reference counting when all responses received.
function gotAllAPIResponses() {
    if (apiTimeout) {
        clearTimeout(apiTimeout);
        apiTimeout = null;
    }
}

==================================================================

That said, a better approach might be to use the "request" node module which has built-in timeouts when doing http requests from node to another server (such as your BigCommerce API server). Look on this page for "timeout" to see an example:

http://www.sitepoint.com/making-http-requests-in-node-js/

==================================================================

Thirdly, instead of doing your own reference counting you should look into "promises" and specifically the ".all" functionality. It allows you to do a bunch of things and only call the callback once everything completes. For instance, here's a question/answer referencing that exact functionality (with a timeout) using Angular:

http://stackoverflow.com/questions/19900465/angularjs-q-all-timeout
John Q
  • 1,262
  • 2
  • 13
  • 19