2017-04-12 60 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是如何工作的。