Mir*_*ko 3 javascript node.js http-request
我在循环中发出HTTP请求时遇到了一些麻烦.
让我解释一下我的内容......
我创建一个http GET来检索一些值,然后我需要为我刚刚从第一个请求获取的每个值创建另一个HTTP GET.
两个调用for都没问题,如果我切断循环并尝试运行整个请求链,它就可以完美地工作,但是自从我删除循环后只有一次.我怎样才能使它工作?
这是代码:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
我希望我对这个问题很清楚.
这里的问题是Javascript范围和拼写错误之一.
首先,你硬编码的数组索引body[0]和body[1].看起来你的意思是他们是循环变量.
第二,在简化的伪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;
});
}
Run Code Online (Sandbox Code Playgroud)
所有Web请求都是异步的.曾经有一种方法可以强制它们同步运行,但在大多数主流浏览器中都不推荐使用它.这意味着发出请求,并且可能在实际代码之外得到响应,然后调用某种回调 - 在这种情况下,是匿名内部函数function(result){...}.
这意味着for循环在请求发生时继续执行并循环,这意味着如果请求不够快,current将在请求返回时更新并且不同,for循环变量也是如此.
我遇到的这类问题的解决方案是在for循环中确定内部请求的函数.
而不是直接在for循环中创建新请求,而是将其移出到自己的函数:
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;
});
}
Run Code Online (Sandbox Code Playgroud)
每次GetMyResourceData调用该函数时,都会为该函数创建一个新范围,因此current当您到达回调时,该函数中的变量将被保留.
所以,这就是我建议你为你的代码做的事情.将for循环外的第二个请求移动到其自己的范围中.
| 归档时间: |
|
| 查看次数: |
15945 次 |
| 最近记录: |