javascript - 如何在 Javascript 中访问闭包内的变量

标签 javascript node.js closures weather-api

我正在使用 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/

相关文章:

javascript - HTML/CSS : Display image at % screen width *up to* original width

javascript - NestJS createParamDecorator 返回未定义

function - 返回一个函数 vs 返回一个闭包

Lua:函数闭包是局部函数吗?

javascript - Kendo Checkbox 检查事件

javascript - JQuery 选择器比 DOM 属性更安全吗?

javascript - 基于递归目录的回调 - Node.js

node.js - 运行 Npm install 时出现 NPM ENOENT 错误

javascript - 我不明白以下javascript代码:的意义

javascript - Rhino JS 解释器与 SpiderMonkey 解释器 - 不同的返回值