0

I'm currently trying to refactor my code and moving specific functions into another file. However, when I try to return an object from this function it returns an empty object, if I print it it will return the entire object. Not sure what's going on.

module.exports = {
// Allrecipes.com webscraper
allRecipes: function(url, user){
    let allRecipeRecipe = new Object();
    request(url, (error, response, html) => {
        if (!error && response.statusCode == 200) {
            const $ = cheerio.load(html);
            let title = $('.headline-wrapper').text().trim();
            let ingredientList = [];
            let instructionList = [];
            let picture = $('div[class="image-container"]').children().attr('data-src');
            $(".ingredients-section li").each((i, el) => {
                ingredientList.push($(el).text().trim());
            });
            $(".instructions-section p").each((i, el) => {
                instructionList.push($(el).text());
            });
            let id = uuid.v4();
            let times = [];
            $('.recipe-meta-item-body').each((i, el) => {
                times.push($(el).text().trim());
            });
            let totalTime = times[2];
            let totalServings = times[3];
            allRecipeRecipe._id = id;
            allRecipeRecipe.title = title;
            allRecipeRecipe.user = user;
            allRecipeRecipe.pictureLink = picture;
            allRecipeRecipe.ingredientList = ingredientList;
            allRecipeRecipe.instructionList = instructionList;
            allRecipeRecipe.time = totalTime;
            allRecipeRecipe.servings = totalServings;
        }
    });
    return allRecipeRecipe;
},
}
  • Sorry I edited it, it was supposed to be allRecipeRecipe. In that case the literal [1,2,3,4,5,6] is returned – pikachungg Apr 24 '21 at 20:10
  • The ```allRecipeRecipe``` object properties are being set in the callback function which gets called after the request returns, whereas the ```return``` returns immediately. That is why it's empty. – Clinton Chau Apr 24 '21 at 20:14

0 Answers0