How to store JSON response in variable in Node.js?

6.8k views Asked by At

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.

2

There are 2 answers

2
r0ck On BEST ANSWER

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!

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)
}

Consider this is not a good approach for coding in async.

3
Patrick Hund On

request is asynchronous. If you want to write asynchronous code in this way, you should use an API that returns a Promise, e.g. axios. You can then use async/await to write your code.