2016-12-30 10 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() 
    }); 
} 

Observablesを使用している場合は、ジェネレータのようなESNext機能やさらに好きな機能を使用することもできます。

関連する問題