0

I am using the request library in javascript.

If I use

function executeYQL(q) {
  const uri = 'http://query.yahooapis.com/v1/public/yql'
  const qs = {
    q: encodeURIComponent(q),
    format: 'json',
    env: 'http://datatables.org/alltables.env'
  };
  request(uri, qs, (err, res, body) => {
    if (!err && res.statusCode === 200) {
      return JSON.parse(body);
    } else {
      console.log(res.statusCode);
      console.log(err);
    }
  });
};

exports.getStocks = (req, res) => {
  const q = 'select * from yahoo.finance.historicaldata where symbol = "YHOO" AND startDate = "2009-09-11" and endDate = "2010-03-10"';
  const json = executeYQL(q);
  res.json(json);
};

it results in status code 400, but if I use

const uri = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(q) + '&format=json&env=http://datatables.org/alltables.env'

it retrieves the data correctly; however, the variable json inside getStocks() is undefined.

I don't know why it's not populated. Do I have to use Promise? I guess it's because of synchronous call, so it runs res.json(json) before const json = executeYQL(q) is done?

How do I make my code in each line wait until the code previous lines are executed?

Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • 1
    `the variable json inside getStocks() is undefined` - that's because `executeYQL` doesn't return anything – Jaromanda X Aug 14 '16 at 11:02
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Yury Tarabanko Aug 14 '16 at 11:07
  • Doesn't mention the problem with querystrings – Jamgreen Aug 14 '16 at 11:51
  • It's still the same fundamental misunderstanding: `request` takes a callback that gets executed *later* when the result becomes available - i.e. it doesn't "wait" for the result - so it'll be `undefined` until that has happened. – jib Aug 15 '16 at 13:56
  • You could use [fetch](http://stackoverflow.com/q/32721850/918910). – jib Aug 15 '16 at 14:21

0 Answers0