Thursday 9 August 2018

javascript - Node.js use returned object from async function

I'm new on Node.js, I want to scrap some data from other website that no legal issue related, But there is some problem because of Node.js's asynchronous. Please see below code that request to some url and parsing document using Cheerio.js.




function getPrices() {
var url = "http://some-price-list-url.com";

request(url, function (err, res, html) {
var $ = cheerio.load(html);
var prices = {};

for(var i=0; i<10; i++){
prices[i] = $(span[class="someSelector"]);
}


return prices;

});

}


No problem with above code, So I want to display returned object, so




var prices = getPrices();

console.log(prices); // ---> undefined


I want to display to console the returned object, but it shown undefined. I test same structure code without stream task, It works well. So I guess the console.log tried before getPrices() not yet completed. How can I show this object properly?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...