Nodejs - 响应问题

时间:2017-04-12 11:32:47

标签: google-places-api

//我无法将https.get中的数据转换为变量 //我们需要将httpd返回值分配给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 */
    });;

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

1 个答案:

答案 0 :(得分: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的工作原理。