简体   繁体   English

嵌套请求被阻止

[英]Nested requests are blocking

I am relatively new to nodejs. 我对Node.js比较陌生。 I've been recently pooling all of the collective knowledge i've gathered through the past couple of months into an project. 最近,我一直将过去几个月中收集到的所有集体知识集中到一个项目中。 I believe I've ran into my first "blocking" issue in nodejs. 我相信我在Node.js中遇到了我的第一个“阻塞”问题。

I have a page that loads two request() calls they are async and nested accordingly. 我的页面加载了两个request()调用,它们是异步的并相应地嵌套。 The innermost one uses data from the innermost to redirect the user. 最内层使用来自最内层的数据来重定向用户。

  request(parameters,function(error, response, data){
      //the first request passes a token  
      request(newParamters,function(error, response, data){
          //the second request passes a url
          res.redirect(data.info.url);
      });
  });

The error is that when I open this up in many browser tabs it ends up breaking after the first couple then the server says data.info.url is undefined. 错误是,当我在许多浏览器选项卡中打开它时,它在第一对夫妇之后最终破裂,然后服务器显示data.info.url未定义。

My question to you is: Should I only be performing one request at a time? 我对您的问题是: 我一次只能执行一个请求吗? I could save the token from the first request() and redirect the user to the second request() would this help? 我可以从第一个request()保存令牌,然后将用户重定向到第二个request()会有所帮助吗? I've been very conscience about async and not blocking and I'm shocked that this is happening. 我一直对异步和不阻塞感到非常良心,对此感到震惊。 Any feedback would be great! 任何反馈将是巨大的!

Nesting like this is going to lead to many problems. 这样的嵌套将导致许多问题。

I prefer this pattern, way I break-up everything to named functions that are much easier to read. 我更喜欢这种模式,将所有内容分解为易于阅读的命名函数。

When a function completes it calls the next and so on. 函数完成后,将调用下一个,依此类推。

parameters = {};   //define parameters
first(parameters); // call first function to kick things off.

var first = function(parameters) {

      request(parameters,function(error, response, data){
         newParamters = date.something;        
         second(newParamters, data); //call second function         
     });
};

var second = function(newParamters, data){

      request(newParamters,function(error, response, data){
          res.redirect(data.info.url);
     });
}

This pattern is "non-blocking", so when the first request is made the nodejs process exits and continues when the response is received only then will the second function get called. 这种模式是“非阻塞的”,因此当发出第一个请求时,nodejs进程退出,并在接收到响应时继续,然后才调用第二个函数。

When the second request is made the nodejs process exits again. 当发出第二个请求时,nodejs进程再次退出。 The redirect will only occur after the response is received. 重定向将仅在收到响应后发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM