Thursday, April 26, 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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...