Nested requests are blocking

2019-02-18 20:05发布

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条回答
三岁会撩人
2楼-- · 2019-02-18 21:04

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.

查看更多
登录 后发表回答