Home > Software design >  Function does not pass object to the constant
Function does not pass object to the constant

Time:11-16

I'm new to javascript so maybe it's a dumb mistake. I'm trying to pass the values ​​of the object that I get in this webscrapping function to the constant but I'm not succeeding. Every time I try to print the menu it prints as "undefined". `

const puppeteer = require("puppeteer");

async function getMenu() {
    console.log("Opening the browser...");
    const browser = await puppeteer.launch({
        headless: true
    });
    const page = await browser.newPage();
    await page.goto('https://pra.ufpr.br/ru/ru-centro-politecnico/', {waitUntil: 'domcontentloaded'});
    console.log("Content loaded...");

    // Get the viewport of the page
    const fullMenu = await page.evaluate(() => {
        return {
            day: document.querySelector('#conteudo div:nth-child(3) p strong').innerText,
            breakfastFood: document.querySelector('tbody tr:nth-child(2)').innerText,
            lunchFood: document.querySelector('tbody tr:nth-child(4)').innerText,
            dinnerFood: document.querySelector('tbody tr:nth-child(6)').innerText
        };
    });

    await browser.close();
    
    return {
        breakfast: fullMenu.day   "\nCafé da Manhã:\n"   fullMenu.breakfastFood,
        lunch:     fullMenu.day   "\nAlmoço:\n"   fullMenu.lunchFood,
        dinner:    fullMenu.day   "\nJantar:\n"   fullMenu.dinnerFood
    };
};

const menu = getMenu();
console.log(menu.breakfast);

`

I've tried to pass these values ​​in several ways to a variable but I'm not succeeding. I also accept other methods of passing these strings, I'm doing it this way because it's the simplest I could think of.

CodePudding user response:

Your getMenu() is an async function. Can you try to put await getMenu().

CodePudding user response:

I have no access to the package that you imported. You may try changing the last part of your code to:

const menu = await getMenu();
if (menu) {
    console.log(menu.breakfast);
 }

Explanation

getMenu() and await getMenu() are different things in JS. getMenu() is a Promise Object which does not represent any string / number / return value. await getMenu() tells JS to run other code first to wait for the result of getMenu().

Despite await tells JS to wait for getMenu() to be resolved, it doesn't stop console.log(menu.breakfast) from running. Your code will try to access menu - which at that moment it is a Promise object. Therefore, breakfast property doesn't exist in the Promise object, so you get undefined.

By adding a if (menu) {...} statement, javascript will wait until menu is resolved before going inside the if-statement. This is useful when you want to do console.log() on a async/await return value.

  • Related