嵌套的请求被封锁 [英] Nested requests are blocking

查看:211
本文介绍了嵌套的请求被封锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的的NodeJS。最近我一直在汇集所有的集体知识我已经通过过去几个月的聚集成一个项目。我相信我已经跑进我的NodeJS第一堵的问题。

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);
      });
  });

该错误是,当我在很多浏览器标签页打开这个了它最终打破了第一对夫妇,则服务器后说 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? 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.

我preFER这种模式,这样我分手一切命名功能,这些功能更容易阅读。

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);
     });
}

此模式是非阻塞的,因此,当第一个请求是由所述的NodeJS进程退出和接收时的响应才将第二函数被调用继续。

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. The redirect will only occur after the response is received.

这篇关于嵌套的请求被封锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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