javascript - Getting undefined for function call in Express render() -
this question has answer here:
i'm new node , express, , running trouble getting data 1 function, pass function var. presume because not handling callback , async stuff properly, appreciate steer.
the code should explanatory. attempting retrieve json data url, , pass router.get function's render() method. however, nothing ("undefined") gets sent instead. when run getdata() function separately, however, returns correct data, stated, presume because i'm not handling 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 json response return body._embedded.assets } }); } /* 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 @ moment limit: limit, activatesharetools: activatesharetools, cid: cid, cardsheader: req.query.cardsheader, }); });
any guidance appreciated.
request asynchronous function, need add callback data , execute after completes request, this:
function getdata (cid, callback) { var request = require("request"); var cid = 'xxxxxx'; var baseurl = "someurl.com"; var apikey = "xxxxxx"; var curl = baseurl + cid + '?api_key=' + apikey request({url: curl, json: true}, callback); } router.get('/', function (req, res) { var cid = req.query.cid ? req.query.cid : '14d115ff-1db7-4a6f-8648-ea64bc1a6597'); var limit = number(req.query.limit); getdata(cid, function (error, response, body) { if (!error && response.statuscode === 200) { res.render('index', { title: 'cards', cards: body._embedded.assets.slice(0, limit), <--- returning undefined @ moment limit: limit, activatesharetools: activatesharetools, cid: cid, cardsheader: req.query.cardsheader, }); } else { throw error; } }); });
Comments
Post a Comment