This question already has answers here:
Using async/await with a forEach loop
                                
                                    (18个回答)
                                
                        
                                去年关闭。
            
                    
我认为我将我的driver.get(site)调用设置为错误,因为它们都在同一时间执行。我试图让硒访问一个站点,做一些逻辑,稍停片刻,然后通过访问另一个站点重新开始。不幸的是,这一切都是同时发生的,导致浏览器在页面加载后立即重定向到数组中的下一个站点。

let webdriver = require("selenium-webdriver");
    let sites = [
    'https://www.site1.com'
    , 'https://www.site2.com'
    , 'https://www.site3.com'
];
let driver = new webdriver.Builder().usingServer().withCapabilities({'browserName': 'chrome' }).build();
sites.forEach(site => {
    driver.get(site).then(x => {
        //   perform a mixture of send keys, clicks, and a mandatory delay
        Promise.all([
            promise1
            , promise2
            , driver.sleep(1000)
        ]).then(y => {

        }).catch(err => {

        })
    })
})

最佳答案

使用递归方法并从.then(y => {})调用函数

let webdriver = require("selenium-webdriver");
let sites = [
    'https://www.site1.com'
    , 'https://www.site2.com'
    , 'https://www.site3.com'
];
let driver = new webdriver.Builder().usingServer().withCapabilities({'browserName': 'chrome' }).build();

function doCheck( sites, ind ) {
    driver.get(sites[ind]).then(x => {
        //   perform a mixture of send keys, clicks, and a mandatory delay
        Promise.all([
            promise1
            , promise2
            , driver.sleep(1000)
        ]).then(y => {
            if (sites.indexOf(sites[ind++]) !== -1){
                doCheck(sites, ind++);
            }
        }).catch(err => {

        })
    })
}

doCheck( sites, 0 );

10-05 20:43