【发布时间】:2017-05-22 19:24:26
【问题描述】:
我正在努力从 API 获取响应并将其保存在变量中以便在 Node.js 中进一步使用它。也许我不知道语言是如何工作的。问题来了:
// Objective, get current temperature of New Delhi in celcius
var request = require('request');
var url = "http://api.openweathermap.org/data/2.5/weather?id=1261481&appid=#####&units=metric";
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
curTemp = JSON.parse(body).main.temp; // curTemp holds the value we want
}
})
// but I want to use it here
console.log(curTemp);
我想将来自 openweathermap(即body.main.temp)的 JSON 响应存储到一个变量中。然后我将根据当前温度撰写推文。
【问题讨论】:
-
也许你可以在回调中发推文?
-
一个常见的异步问题,当您尝试打印
curTemp时,该变量很可能未定义,因为 HTTP 请求尚未完成。所以使用回调或承诺或将依赖于curtemp的代码包装到同一范围内。
标签: javascript json node.js openweathermap