async function is not waiting at await

479 views Asked by At

I need to scroll down before doing some action. my promise function is not waiting in await line. how can I solve this problem?

let scrollingPromise = new Promise(async (resolve, reject) => {

    // I need this part to be done before resolving
    await page.evaluate(() => {
        const scrollingWindow = document.querySelector('.section-layout.section-scrollbox.scrollable-y.scrollable-show');
        var scrollCount = 0;

        function scrollFunction(){
            setTimeout(()=>{
                scrollingWindow.scrollBy(0, 5000);
                scrollCount++;
                if(scrollCount < 5){
                    scrollFunction();
                }
            }, 3000);
        };

        scrollFunction();

    });
    // but it resolves instantly doesn't wait for previous await
    resolve();
});

//this .then() runs before my scrolling
scrollingPromise.then(async () => {
    // ...
}
1

There are 1 answers

7
Jeremy Thille On

You're mixing await and Promise syntaxes. You're awaiting an asynchronous function that doesn't return a Promise, so it can't work. I believe you're trying to do this :

let scrollingPromise = new Promise((resolve, reject) => {
    page.evaluate(() => {
        const scrollingWindow = document.querySelector('.section-layout.section-scrollbox.scrollable-y.scrollable-show');
        var scrollCount = 0;

        function scrollFunction() {
            setTimeout(() => {
                scrollingWindow.scrollBy(0, 5000);
                scrollCount++;
                if (scrollCount < 5) {
                    scrollFunction();
                } else {
                    resolve() // <-- Done, resolve here
                }
            }, 3000);
        };

        scrollFunction();
    });
});