I am struggling to get response from API and save it in variable to use it further in Node.js. Maybe I don't know how the language works. Here is the problem:
// 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);
I want to store JSON response from openweathermap (i.e. body.main.temp
) to a variable. Then I'll be composing a tweet out of current temperature.
In Node.js, it's all about callback (or functions you need to call later). So all you need to is create is a tweet function and call it when you got your data!
Consider this is not a good approach for coding in async.