2017-04-12 51 views
0

//我无法从https.get中获取数据到变量中 //我们需要将httpd返回值指定给global.city变量。Nodejs - 问题与响应

global.city ; 
    https.get(url, function(response) { 
    var body =''; 
    response.setEncoding("utf8"); 
    response.on('data', function(chunk) { 
     body += chunk; 
     //console.log(body); 
    }); 

    }).on('error', function(e) { 
    console.log("Got error: " + e.message); 
    }).on('response',function(f){ 
    console.log("lets dance"); 
    }).on('end', function() { 
     var places = JSON.parse(body); 
     locations = places.results; 
     return locations ; 
     global.city = locations ; // I get the data here. 
     console.log(global.city); 
     /* the data is seen here */ 
    });; 

    console.log(global.city); // No response outside the function. 

回答

0

的数据异步检索,所以当你打印出结果(console.log(global.city);)的数据尚未公布。

这是你如何做到这一点:

global.city ; 
    https.get(url, function(response) { 
    var body =''; 
    response.setEncoding("utf8"); 
    response.on('data', function(chunk) { 
     body += chunk; 
     //console.log(body); 
    }); 

    }).on('error', function(e) { 
    console.log("Got error: " + e.message); 
    }).on('response',function(f){ 
    console.log("lets dance"); 
    }).on('end', function() { 
     var places = JSON.parse(body); 
     locations = places.results; 
     return locations ; 
     global.city = locations ; // I get the data here. 
     console.log(global.city); 
     /* the data is seen here */ 
     goOn(); 
    });; 

function goOn() { 
    // continue your code here 
    console.log(global.city); // global.city has value now 
} 

希望这会有所帮助,但我建议你看看的Javascript是如何工作的。