在函数外部使用变量

时间:2014-10-31 22:05:53

标签: javascript node.js

我首先要说的是,我真的想学习节点,但遇到了一些困难。我正在构建一个调用API的超级简单的Weather App,然后我想返回数据。

但我不确定为什么它不会将这些数据返回到控制台?

var request = require('request');

request('https://api.forecast.io/forecast/{API KEY}/42.47994,-83.13040', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      //var info = JSON.parse(body);
      var jsonObject = JSON.parse(body);
      var summary = jsonObject.currently.summary;
      var temp = jsonObject.currently.temperature;
      var realFeel = jsonObject.currently.apparentTemperature;
      var summary2 = jsonObject.hourly.summary;
      var max = jsonObject.daily.data[0].temperatureMax;
      var min = jsonObject.daily.data[0].temperatureMin;
    }
})
console.log('Todays forecast ' + summary2 + ' With a current Tempature of ' + temp + '. But feels like ' +realFeel + ' With a high of '+max+' and a low of '+min);

3 个答案:

答案 0 :(得分:3)

Node是异步服务器。当您执行要阻止的请求时,节点引擎继续执行以下代码。您正在向请求模块传递回调函数,但是在请求被触发之后以及之前返回结果时,您的console.log正在执行。

您要做的是将代码放在回调函数中使用数据的位置。

var request = require('request');

request('https://api.forecast.io/forecast/{API KEY}/42.47994,-83.13040', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      //var info = JSON.parse(body);
      var jsonObject = JSON.parse(body);
      var summary = jsonObject.currently.summary;
      var temp = jsonObject.currently.temperature;
      var realFeel = jsonObject.currently.apparentTemperature;
      var summary2 = jsonObject.hourly.summary;
      var max = jsonObject.daily.data[0].temperatureMax;
      var min = jsonObject.daily.data[0].temperatureMin;
      console.log('Todays forecast ' + summary2 + ' With a current Tempature of ' + temp + '. But feels like ' +realFeel + ' With a high of '+max+' and a low of '+min);
    }
})

你也不应忽视错误。

var request = require('request');

request('https://api.forecast.io/forecast/{API KEY}/42.47994,-83.13040', function (error, response, body) {
    if (error) throw error;
    if (response.statusCode != 200) return console.log('Invalid status code: '+response.statusCode)                     
    var jsonObject = JSON.parse(body);
    var summary = jsonObject.currently.summary;
    var temp = jsonObject.currently.temperature;
    var realFeel = jsonObject.currently.apparentTemperature;
    var summary2 = jsonObject.hourly.summary;
    var max = jsonObject.daily.data[0].temperatureMax;
    var min = jsonObject.daily.data[0].temperatureMin;
    console.log('Todays forecast ' + summary2 + ' With a current Tempature of ' + temp + '. But feels like ' +realFeel + ' With a high of '+max+' and a low of '+min);
});

答案 1 :(得分:0)

所有变量都是回调函数的本地变量。将console.log语句移动到函数中。

如果您希望所有变量都是全局的(坏主意),请从回调函数中删除var语句:

(function (){ // add this line
  var request = require('request');
  var summary, temp, realFeel, summary2, max, min;

  request('https://api.forecast.io/forecast/{API KEY}/42.47994,-83.13040', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      //var info = JSON.parse(body);
      var jsonObject = JSON.parse(body);
      summary = jsonObject.currently.summary;
      temp = jsonObject.currently.temperature;
      realFeel = jsonObject.currently.apparentTemperature;
      summary2 = jsonObject.hourly.summary;
      max = jsonObject.daily.data[0].temperatureMax;
      min = jsonObject.daily.data[0].temperatureMin;

      console.log('Todays forecast ' + summary2 + ' With a current Tempature of ' + temp + '. But feels like ' +realFeel + ' With a high of '+max+' and a low of '+min);
    }
  });
}()); // and this line to avoid global variables

但是,您仍需要一段代码来显示天气摘要。您的帖子中回调函数之外的console.log将在数据从预测服务返回之前运行。简而言之,您必须将console.log放在回调函数中。

这个答案直接回复了您的具体问题。请理解创建global variables is an anti-pattern

答案 2 :(得分:0)

问题在于,当您使用var声明变量时,您声明它的作用域是您所在的函数。如果您使用名称而不使用var声明它,它将在全局中查找它们“窗口”范围。

在回调函数中删除var关键字,该函数应该改变全局范围。