1

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.

The Pied Pipes
  • 1,425
  • 2
  • 16
  • 29
  • There is no return from getData(); LiveCards will be `undefined`. – Sam Greenhalgh Dec 16 '14 at 09:29
  • hmm. ok. I'm trying to `return body._embedded.assets`. Is that not going to return the data? – The Pied Pipes Dec 16 '14 at 09:31
  • No, it's not going to return the data. Your `get_data` function does not have any `return` statement in it. When you run the function separately, you only see the `console.log` but not the return value. – Bergi Dec 16 '14 at 09:33

1 Answers1

1

request is asynchronous function, you need add callback to get Data and execute it after completes the request, like 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 at the moment
        limit: limit,
        activateSharetools: activateSharetools,
        cID: cID,
        cardsHeader: req.query.cardsHeader,
      });
    } else {
      throw error;
    }
  });
});
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144