Monday, 1 May 2017

Know when my function is over

This is my functions

function parseLinks(links, callback) {

    var products = [];
    for (var i = 0; i < links.length; i++) {
        request(links[i], function (error, response, body) {
            var product;
            if (!error && response.statusCode == 200) {
                var $ = cheerio.load(body);

                // title
                var title = $('h1').text();
                if (!title)
                    var title = $('title').text();

                var description = $('meta[name="description"]').attr('content');

                product = new Product(links[0].trim(), title.trim(), description.trim());
                products.push(product);
            }
        });
    }
    callback(products) // the callback only do a console.log(products)
}

After that, I want to do a console.log(products) who display all the products. So I setup a callback attached to parseLinks and call it after the for loop. The problem is in my for loop, I call asynchronous function request each times, so my callback is called before the end of all the request calls, so my console.log(products) print an empty array.

Do you know how fix that ? Thanks



via Tech

No comments:

Post a Comment