'How to make puppeteer return something different if a specific element gets loaded

I'm trying to get values from a page using puppeteer, the main goal is to extract a URL if the content is valid, however the page might return an error inside of a p tag.

async function example() {
    const browser = await puppeteer.launch({
        headless: true,
    });
    const page = await browser.newPage();
    await page.goto('https://example.com');
    
    // The page might load an error inside of a p element
    // I don't want to block the rest of the script using await
    page.waitForSelector('p', {timeout: 5000})
    .then( async () => {
        const pString = await page.evaluate(() => {
            return document.querySelector('p').innerHTML;
        });
        console.log(pString);
        if(pString.includes('error')) {
            console.log('Page contains an error');

            //i need to make the main function 'return' if this happens
        }
    })

    // Wait for the link to load if everything is ok
    await page.waitForSelector('a', {timeout: 5000});
    const link = await page.$('a');

    // other stuff
}

I can't figure out a proper way of doing this without having to wait for the timeout



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source