0

I'm building a messenger bot that queries an API once a day and sends the information contained there to users. it's hosted on Heroku and uses Node.js

I'm currently using this to query the API:

var request = require('request');
//url for classes JSON
var url = 'https://example.api';

//get JSON, parse it and store it in jsonstorage variable
request(url, (error, response, body)=> {
    if (!error && response.statusCode === 200) {
    jsonstorage = JSON.parse(body)
    console.log("Got a response")
} else {
    console.log("Got an error: ", error, ", status code: ", response.statusCode)
}
})

The problem with this is that it doesn't refresh the API query ever, so the values returned are always the same. If I try and put it within the functions that send the data once a day though, it claims the jsonstorage variable is 'undefined'.

How can I refresh the query regularly?

Thanks!

Fede B
  • 5
  • 1
  • 3
  • Is that all your code? It seems your `jsonstorage` variable is defined in the scope of the request function, therefore it will be not available for outside functions. – Lucas Lazaro Oct 03 '16 at 21:59
  • Also if you are trying to persist data, you may want to store it in a DB and not in a variable within your code. – Lucas Lazaro Oct 03 '16 at 22:00
  • There's more to it but the jsonstorage variable is able to be accessed in another function even though it is contained within the scope of the function. I've tried to take it out when I migrate it inside a function but that still throws an error. Got this from the second answer here [link](http://stackoverflow.com/questions/11826384/calling-a-json-api-with-node-js). Also I don't want the variable to persist - just to be able to call it within a function multiple times @LucasLazaro – Fede B Oct 03 '16 at 22:07

1 Answers1

0

Found an answer to this myself - the issue I was running into was that request is asynchronous, so I needed to wait for request to receive a result before running the rest of the script.

Fede B
  • 5
  • 1
  • 3