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

て烟熏妆下的殇ゞ 提交于 2019-12-13 18:51:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19739945/node-http-requests-are-executing-out-of-order-causing-problems-with-an-api-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!