2016-12-30 38 views
0

我正在使用Node.js創建天氣應用程序來訪問當前天氣。如何在Javascript中使用閉包訪問變量

當我調用openweatherapp API,通過我試圖傳遞給module.exports的JSON檢索到的溫度可變嵌套一系列閉合的功能之內。

有什麼辦法可以讓我訪問temperature並通過module.exports,這樣我就可以從另一個文件中檢索數據了嗎?

var http = require('http') 

const apiKey = "myAPIkey" 

// Connect to API URL api.openweathermap.org/data/2.5/weather?q={city name} 
function accessWeather(city, callback) { 

    var options = { 
    host: "api.openweathermap.org", 
    path: "/data/2.5/weather?q=" + city + "&appid=" + apiKey + "", 
    method: "GET" 
    } 

    var body = "" 

    var request = http.request(options, function(response) { 

    response.on('data', function(chunk) { 
     body += chunk.toString('utf8') 
    }) 
    response.on('end', function() { 

     var json = JSON.parse(body) 
     var temperature = parseInt(json["main"]["temp"] - 273) 
    }) 
    }) 
    request.end() 
} 

temp = accessWeather("Calgary") 
console.log(temp) 

module.exports = { 
    accessWeather: accessWeather 
} 

回答

1

那麼在這裏,我們有一個關於異步在JavaScript中如何工作的誤解。您無法返回將來要加載的數據。

有幾個選項可以解決這個問題。

1)導出函數接受另一個函數作爲參數,調用函數時解決您的數據:

module.export = function accessWeather(city, callback) { 

    var options = { 
    host: "api.openweathermap.org", 
    path: "/data/2.5/weather?q=" + city + "&appid=" + apiKey + "", 
    method: "GET" 
    } 

    var body = "" 

    var request = http.request(options, function(response) { 

    response.on('data', function(chunk) { 
     body += chunk.toString('utf8') 
    }) 
    response.on('end', function() { 

     var json = JSON.parse(body) 
     var temperature = parseInt(json["main"]["temp"] - 273); 
     callback(temperature); 
    }) 
    }) 
    request.end() 
} 

2)由於回調風格是傳統的,現在,你甚至可以更好地做一些事情承諾。

module.export = function accessWeather(city, callback) { 

    return new Promise(function(resolve, reject){ 
    var options = { 
    host: "api.openweathermap.org", 
    path: "/data/2.5/weather?q=" + city + "&appid=" + apiKey + "", 
    method: "GET" 
    } 

    var body = "" 

    var request = http.request(options, function(response) { 

    response.on('data', function(chunk) { 
     body += chunk.toString('utf8') 
    }) 
    response.on('end', function() { 

     var json = JSON.parse(body) 
     var temperature = parseInt(json["main"]["temp"] - 273); 
     resolve(temperature); 
    }) 
    }) 
    request.end() 
    }); 
} 

您還可以使用像發電機這樣的ESNext功能,如果使用Observables,我更喜歡使用ESNext功能。

相關問題