简体   繁体   中英

Selenium WebdriverJS Promise Loop

I'm trying to look for the "More" link in a container to keep clicking on it until the link is no longer there. I'm creating a deferred and returning it with the fulfill call happening once there is no longer a "More" link available.

.then(function (previousResults) {
    var deferred = webdriver.promise.defer();

    // look for the more link, keep clicking it till it's no longer available
    browser.wait(function() {
        // see if we have "more" to click on
        browser.findElements(byMoreLinkXpath)
            .then(function (moreLinks) {
                if (moreLinks[0]) {
                    console.log('has more');
                    moreLinks[0].click()
                        .then(function() {
                            // check for spinner to go away
                            browser.wait(pageDoneLoading, configSetting.settings.testTimeoutMillis);
                        });
                } else {
                    console.log('no more');
                    deferred.fulfill(true);
                }
            });
    }, 5000);

    return deferred.promise;
})

Unfortunately, the promise is never fulfilled it simply times out. I tried doing a return deferred.promise; in the else block and while it works for reject , it still doesn't work for fulfill .

the syntax of webdriver.wait :

wait(condition, opt_timeout, opt_message)

but in your code, the first argument is neither a condition nor a promise but a function , so I would change it to:

also, I think what you are doing here is promise anti-pattern( also I am not seeing the loop of checking again for more links, sorry but I think you do not completely understand driver.wait ), I would simply reduce the above function as:

function exhaustMoreLinks(){
    return driver.wait( until.elementLocated(byMoreLinkXpath), 5000)
        .then(function(){
            return driver.findElement(byMoreLinkXpath);
        }).then(function(moreLink){
            console.log('more links');
            return moreLink.click();
        }).then(function(){
                return browser.wait(pageDoneLoading(), configSetting.settings.testTimeoutMillis).then(exhaustMoreLinks);
            }, function(err){
            if(err.name === 'NoSuchElementError' || (err.message.search(/timed out/i)> -1 && err.message.search(/waiting element/i) > -1) ){    // checking if error because time-out or element not found, if true, redirect to fulfil
                console.log('no more links');
                return;
            }else{
                throw err;
            }
        });
}

and usage would be like:

...
.then(exhaustMoreLinks)
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM