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?