Node http requests are executing out of order causing problems with an API using a nonce value

StackOverflow https://stackoverflow.com/questions/19739945

  •  03-07-2022
  •  | 
  •  

Pergunta

I am making http requests to an external API that requires each request to have an ever increasing nonce value.

The problem I am experiencing is that even though the requests are submitted in order, they are not getting popped off the call stack in order (presumably). I am using the request library. A portion of my helper method looks like this:

Api.prototype.makeRequest = function(path, args, callback) {
    var self = this;
    var nonce = null;
    var options = null;

   // Create the key, signature, and nonce for API auth
   nonce = (new Date()).getTime() * 1000;
   args.key = self.key;
   args.signature = ( ... build signature ... );
   args.nonce = nonce;

   options = {
            url: path,
            method: 'POST',
            body: querystring.stringify(args)
   };

   request(options, function(err, resp, body) {
       console.log('My nonce is: ' + args.nonce);
       .
       . 
       .
   });
};

The console log results in a nonce order that is not ever increasing, but jumbled, even though each request are necessarily created in order (I tested this by placing the console log before the request call). How do I enforce a certain order? Why isn't it already doing this? Any understanding would be much appreciated.

Foi útil?

Solução

Because of the asynchronous nature of Node.js if you make three HTTP requests with three different nonce values like the following

GET http://example.com/?nonce=1
GET http://example.com/?nonce=2
GET http://example.com/?nonce=3

All three request will happen concurrently. Which ever request gets a response back from the server will be the first to complete (i.e its callback will run).

You could incorporate the functions of the async module like async.series or async.map to ensure the requests return in order.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top