节点 http 请求乱序执行,导致使用 nonce 值的 API 出现问题 [英] Node http requests are executing out of order causing problems with an API using a nonce value

查看:45
本文介绍了节点 http 请求乱序执行,导致使用 nonce 值的 API 出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向外部 API 发出 http 请求,该请求要求每个请求都具有不断增加的 nonce 值.

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.

推荐答案

由于 Node.js 的异步特性,如果您使用三个不同的 nonce 值发出三个 HTTP 请求,如下所示

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

您可以合并 async 模块的功能,例如 async.seriesasync.map 确保请求按顺序返回.

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

这篇关于节点 http 请求乱序执行,导致使用 nonce 值的 API 出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆