Saturday, 2 July 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...