简体   繁体   English

Selenium Webdriver-兑现多项承诺

[英]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. 下面的代码有效,除了我不想在解决时只打印出结果,我希望能够以JSON格式构造它们。 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. 但是我不知道如何等待所有的诺言都得到解决,以使我最终的JSON数组。

Promise.all resolves an array so you need to push elements to an array and then pass that to Promise.all function. Promise.all解析数组,因此您需要将元素推入数组,然后将其传递给Promise.all函数。 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. 不知道这段代码是否可以运行,但这只是一个例子,如果您查看Promises的文档,则传递给Promise.all的参数必须是可迭代的。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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