我首先要说的是,我真的很想学习 Node,但遇到了一些困难。我正在构建一个 super 简单的天气应用程序,它调用 API,然后我想返回数据。
但我不确定为什么它不会将此数据返回到控制台?
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);
最佳答案
Node 是一个异步服务器。当你执行一个将要阻塞的请求时, 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);
});
关于javascript - 在函数外部使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26684091/