循环中的Http请求 [英] Http request inside a loop

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

问题描述

我在循环中发出HTTP请求时遇到了一些麻烦。

I'm having some troubles in making a HTTP request inside a loop.

让我解释一下我的内容....

Let me explain what I have....

我创建一个http GET来检索一些值,然后我需要为我刚刚从第一个请求中获取的每个值进行另一个HTTP GET。

I make an http GET to retrieve some values and then I need to make another HTTP GET for each couple of values that I've just taken from the first request.

这两个调用都没问题,如果我为循环切割并尝试运行整个请求链,它运行完美,但只有一次我删除了循环。我怎样才能使它工作?

The two calls are ok, and if I cut the for cycle and try to run the whole request chain it works perfectly, but just one time since I removed the cycle. How can I make it work?

这是代码:

request({
url: "some_url",
    method: "GET",
    json:true,
    headers:[{'content-type': 'application/json'}]
    }, function (error, response, body){
            if(!error & response.statusCode === 200){           
                for(var i=0;i<body.length;i++){
                    for(var j=i;j<body.length-1;j++){
                        //if(i === body.length-1) return;
                        src = body[i].name;
                        dest = body[j+1].name;
                        console.log("sorgente ",sorg);

                        request({
                            url: "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+src+"&destinations="+dest,
                            method: "POST",
                            json:true,
                            headers:[{'content-type': 'application/json'}]
                        }, function (error, response, body){
                            if(!error & response.statusCode === 200){
                                console.log("TIME ",body.rows[0].elements[0].duration.text);
                                return;
                            }else{
                                console.log("google API failed!: ");
                                return;
                            }
                        }); 

                    }
                }

            }else{
                console.log("/google_api failed!: ");
                return;
            }
 });

我希望我对这个问题很清楚。

I hope I was clear with the question.

推荐答案

这里的问题是Javascript范围和拼写错误之一。

The issue here is one of Javascript scoping, and typos.

首先,你硬编码了<$的数组索引c $ c> body [0] body [1] 。看起来你的意思是他们是循环变量。

First, you hardcoded the array indexes of body[0] and body[1]. It looks like you meant for them to be the loop variables.

其次,你的范围问题的概述,简化的伪Javascript:

Second, an outline of your scoping problem, in simplified pseudo-Javascript:

var requestList = [...];

for(var i = 0; i < requestList.length; i++){
    var current = requestList[i];

    // make a request based on current or the data
    // in current. 
    request(..., function(result){
        // do something with the current variable
        current.foo = result.bar;
    });
}

所有Web请求都是异步的。曾经有一种强制它们同步运行的方法,但在大多数主流浏览器中都不推荐使用它。这意味着请求已经完成,并且可能会在实际代码之外得到响应,然后调用某种回调 - 在这种情况下,匿名内部函数功能(结果){...}

All web requests are asynchronous. There used to be a way to force them to run synchronously, but it is deprecated in most major browsers. This means that the request is made, and may get a response, outside of your actual code, and then calls some sort of callback--in this case, the anonymous inner function function(result){...}.

这意味着for循环在发出请求时继续执行并循环,这意味着请求不是很快足够的,当前将在请求返回时更新并且不同,for循环变量也是如此。

What this means is that that for loop continues to execute and loop while the request is being made, meaning if the request isn't fast enough, current will update and be different when the request comes back, and so will the for loop variables.

我遇到的这类问题的解决方案是函数确定for循环中的内部请求。

The solution I've run into for this sort of thing is function scoping out the inner request in the for loop.

不是直接在for循环中创建新请求,而是将其移出到自己的函数中:

Instead of making the new request directly inside the for loop, you move that out to its own function:

var requestList = [...];

for(var i = 0; i < requestList.length; i++){
    var current = requestList[i];

    GetMyResourceData(current);
}

function GetMyResourceData(current){
    request(..., function(result){
        // do something with the current variable
        current.foo = result.bar;
    });
}

每次 GetMyResourceData 函数,为该函数创建一个新范围,因此当您到达回调时,该函数中的当前变量将被保留。

Every time the GetMyResourceData function is called, a new scope is created for that function, so the current variable in that function is held when you reach the callback.

所以,这就是我建议你为你的代码做的事情。将for循环外的第二个请求移动到其自己的范围中。

So, that's what I'd recommend you do for your code. Move the second request outside of the for loop into its own scope.

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

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