I'm new to Node and Express, and am running into trouble getting data from one function, to pass into another function as a var. I presume that this is because I am not handling the callback and async stuff properly, but would appreciate a steer.
The code should hopefully be explanatory. I am attempting to retrieve some JSON data from a URL, and pass it to the router.get function's render() method. However, nothing ("undefined") gets sent instead. When I run the getData() function separately, however, it returns the correct data, so as stated, I presume this is because I'm not handling the async stuff correctly.
function getData(cid){
var request = require("request");
var cid ='XXXXXX' // hard code temp
var baseUrl = "someurl.com"
var apiKey = "XXXXXX"
var cUrl = baseUrl+cid+'?api_key='+apiKey
request({
url: cUrl,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body._embedded.assets); //Print the json response
return body._embedded.assets
}
});
}
/* GET home page. */
router.get('/', function(req, res) {
var LiveCards = getData()
var cID = (req.query.cID
? req.query.cID
: '14d115ff-1db7-4a6f-8648-ea64bc1a6597')
var limit = Number(req.query.limit)
res.render('index', {
title: 'Cards',
cards: LiveCards.slice(0,limit), <--- returning undefined at the moment
limit: limit,
activateSharetools: activateSharetools,
cID: cID,
cardsHeader: req.query.cardsHeader,
});
});
Any guidance appreciated.