【问题标题】:Selenium Webdriver for loop opens many browsers, does not wait for function to completeSelenium Webdriver for循环打开许多浏览器,不等待函数完成
【发布时间】:2018-10-14 11:51:18
【问题描述】:

当我运行以下代码时,150 个浏览器会立即打开 google.com。如何让循环等到函数完成后再打开谷歌?

const {
    Builder, By, Key, until
} = require('selenium-webdriver');
require('chromedriver');

for (let index = 0; index < 150; index++) {
    (async function example() {
        let driver = await new Builder().forBrowser('chrome').build();
        try {
            await driver.get('https://www.google.com/');
        } catch(err) {
            console.log(err);
        } finally {
            await driver.quit();
        }
    })();
}

我尝试使用以下帖子中的代码,但没有成功: JavaScript, Node.js: is Array.forEach asynchronous?, Using async/await with a forEach loop, make async call inside forEach.

提前感谢任何帮助或信息。

【问题讨论】:

    标签: javascript node.js selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:

    仅仅声明和执行 async 函数不会自动让线程等待函数执行 - 您也必须 await 它,否则它会被简单地解释为声明的承诺。

    (async () => {
      for (let index = 0; index < 150; index++) {
        await (async function example() {
          let driver = await new Builder().forBrowser('chrome').build();
          try {
            await driver.get('https://www.google.com/');
          } catch(err) {
            console.log(err);
          } finally {
            await driver.quit();
          }
        })();
      }
    })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多