简体   繁体   中英

Selenium webdriver - resolve multiple promises

The code below works, except for that I don't want to just print out the results when resolved, I would like to be able to structure them in JSON format. I think for that, I need to wait for all promises to get resolved, but I don't know how!

var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;

    var driver = new webdriver.Builder()
        .forBrowser('chrome')
        .build();

    driver.get('www.example.com');
    driver.sleep(2000);

    driver.findElements(By.css('.listing')).then(function(resWraps){
        for (var i=0; i<resWraps.length; i++) {
            resWraps[i].findElement(By.css('.title a')).getAttribute("innerHTML").then(function(title){
                console.log(title);
            });
            resWraps[i].findElement(By.css('.price')).getAttribute("innerHTML").then(function(price){
                console.log(price);
            });    
        }
    });

So, I get a list. Then I'd like to find multiple elements inside each element of the list. But I don't know how to wait for all promises to be resolved in order to make my final JSON array.

Promise.all resolves an array so you need to push elements to an array and then pass that to Promise.all function. Something like:

const promiseArray = []
for (var i=0; i<resWraps.length; i++) {
   promiseArray.push(resWraps[i].findElement(By.css('.title a')).getAttribute("innerHTML"));
}

return Promise.all(promiseArray)
   .then(resolvedList){
 // do something with resolvedList
}

Not sure if this code will run but it's an example, if you look at the documentation for Promises then the argument that is passed to Promise.all has to be iterable.

Hope this helps

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