0

在执行某些操作之前,我需要向下滚动。我的承诺功能没有在等待线中等待。我怎么解决这个问题?

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 () => {
    // ...
}
4

1 回答 1

2

您正在混合await和 Promise 语法。您正在等待一个不返回 Promise 的异步函数,因此它无法工作。我相信您正在尝试这样做:

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();
    });
});
于 2020-10-21T14:37:21.607 回答