我正在努力从 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 响应存储到变量中。然后我将根据当前温度撰写一条推文。
最佳答案
在 Node.js 中,一切都与回调(或稍后需要调用的函数)有关。 因此,您所需要做的就是创建一个 tweet 函数,并在获得数据后调用它!
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
tweet(curTemp)
}
})
// but I want to use it here
function tweet(data){
console.log(data)
}
考虑到这不是异步编码的好方法。
关于javascript - 如何在 Node.js 中的变量中存储 JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41532678/