Nested requests are blocking

瘦欲@ 提交于 2019-11-30 22:48:20

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.

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