Nested requests are blocking

徘徊边缘 提交于 2019-11-30 17:23:41

问题


I am relatively new to nodejs. 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.

I have a page that loads two request() calls they are async and nested accordingly. 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.

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? I've been very conscience about async and not blocking and I'm shocked that this is happening. Any feedback would be great!


回答1:


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.

When the second request is made the nodejs process exits again. The redirect will only occur after the response is received.



来源:https://stackoverflow.com/questions/12101687/nested-requests-are-blocking

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