小弟希望通过调用http的get服务,把返回的response中的某一个link赋值给一个变量然后给后续代码使用。问题是在回调中赋值的结果,在主线程中无法获取。
var url_path;
http.get(options,function(res){
res.on("data",function(chunk){
var data_json = JSON.parse(chunk.toString());
var links = data_json.links;
for (var i = 0;i<links.length;i++){
if (links[i].rel == "down"){
url_path = links[i].href;
console.log(1)
}
}
});
});
};
var second = new Date().getSeconds();
while (new Date().getSeconds() < second+6);
console.log(url_path);
console.log(2)
上面的代码就是希望把某一个rel为down的连接赋值为url_path, 这个http的操作很快的。我在主线程里面尝试了sleep了6秒钟,但是打印出来的url_path还是为undefined。而且奇怪的事情是,我代码中的打印数字的次序也不是我期望的,竟然是先打印2,再打印1,这个是为什么呢。求解啊,求高人帮忙啊