Node HTTP requests run out of order, causing API problems using nonce

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

The problem I am facing is that even if requests are sent in order, they do not exit the call stack in order (presumably). I am using a query library . Part 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 leads to nonce order, which never grows, but mixes up, although each request is necessarily created in order (I checked this by placing the console log before calling the request). How can I apply a specific order? Why doesn't he do that? Any insight would be greatly appreciated.

+1
source share
1 answer

Due to the asynchronous nature of Node.js, if you make three HTTP requests with three different nonce values ​​such as

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

All three queries will be executed simultaneously. Which ever request receives a response from the server will be the first to exit (i.e., its callback will be launched).

You can enable asynchronous module functions, such as async.series or async.map , to ensure that requests are returned in order.

0
source

Source: https://habr.com/ru/post/1239817/


All Articles