我正在使用 Node.js
创建天气应用程序访问当前天气。
当我调用openweatherapp API时,通过 JSON 检索到的温度变量,我试图将其传递给 module.exports
嵌套在一系列闭包函数中。
我有什么办法可以访问 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
}
最佳答案
我们对 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 ) 因为回调风格现在已成为传统,所以您可以使用 Promises 做得更好。
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,我更喜欢它。
关于javascript - 如何在 Javascript 中访问闭包内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41392223/