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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...