2

When I run the following code, 150 browsers are instantly opened to google.com. How can I make the loop wait until the function finishes before opening google again?

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();
        }
    })();
}

I tried using code from the following posts but had no luck: JavaScript, Node.js: is Array.forEach asynchronous?, Using async/await with a forEach loop, make async call inside forEach.

Thanks in advance for any help or info.

1 Answers1

0

Just declaring and executing an async function doesn't automatically make the thread wait until the function executes - you have to await it as well, otherwise it's interpreted simply as a declared promise.

(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();
      }
    })();
  }
})();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320