2

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.

Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118
  • Perhaps you can tweet inside the callback ? – Umang Gupta Jan 08 '17 at 12:41
  • A common async problem, when you try to print the `curTemp` the variable is most likely undefined as the HTTP request isn't finished yet. So use callbacks or promises or wrap the code that depends on the `curtemp` into the same scope. – Risto Novik Jan 08 '17 at 12:43

2 Answers2

1

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.

Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118
r0ck
  • 173
  • 12
0

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.

Patrick Hund
  • 19,163
  • 11
  • 66
  • 95