如何在Javascript中使用闭包访问变量
问题描述:
我正在使用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
}
答
那么在这里,我们有一个关于异步在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功能。