'Promise is not revolved when the condition it's true (?)

I'm not able to understand why the promise is not resolved when the condition it's true. In my case, I'm working with Puppeteer and I'm trying to do scroll down to charge more google reviews. I select all container childs and the total of reviews. It's the same number, but it seems like that condition it's not true. I understand nothing...

My code:

console.log('he entrado');

            await page.evaluate(() => new Promise((resolve) => {

                const scroller = document.querySelector('.review-dialog-list');
                const totalChilds = document.querySelectorAll('.gws-localreviews__general-reviews-block > *').length;
                const totalReviews = document.querySelector('.z5jxId').innerText.slice(0, -8);

                if(totalChilds != totalReviews){
                    var timer = setInterval(() => {
                        scroller.scrollBy(0, 400);
                    }, 100);
                }else{
                    clearInterval(timer);
                    resolve();
                }
            }));

            console.log('he salido');

I can see the console.log with the message 'He entrado' but it never show me 'He salido'. I don't have any problems with the scroller and I check the selectors in browser console and both have the same value.

If somebody can help me or explain to me why my code is failing I'd be thankful. Hope you can understand me and if not, let me know and I will append more details. Thanks a lot!



Solution 1:[1]

You're retrieving the scroller, totalChilds, and totalReviews only when page.evaluate first runs. You should retrieve them every time you scroll instead.

await page.evaluate(() => new Promise((resolve) => {
    const scroller = document.querySelector('.review-dialog-list');
    const timer = setInterval(() => {
        const totalChilds = document.querySelectorAll('.gws-localreviews__general-reviews-block > *').length;
        const totalReviews = document.querySelector('.z5jxId').innerText.slice(0, -8);
        if (totalChilds === totalReviews) {
            clearInterval(timer);
            resolve();
        }
        scroller.scrollBy(0, 400);
    }, 100);
}));

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance