0

I am trying to use the best syntax in a simple .js script that is supposed to make http requests using selenium driver.

I can see the html code retrieved when I use the console.log(ret) inside the function, but if I return the var and try to console.log(getHTML(url)) it just doesn't print. Why is that?

Code below. Comment/Uncomment the console line inside the function to see it printing.

async function getHTML(url){
    try{
        await driver.get(url);
        var ret;
        await driver.getPageSource().then(function(data) { ret = data;});
        driver.quit();
        // console.log(ret);
        return ret;
    }
    catch(err){
        handleFailure(err, driver)
    }
}

var url = 'http://crossbrowsertesting.github.io/selenium_example_page.html';
console.log(getHTML(url));

Initial part of the code in case anyone wants to replicate it:

var chrome = require('selenium-webdriver/chrome');
var firefox = require('selenium-webdriver/firefox');
var {Builder, By, Key, until} = require('selenium-webdriver');

var screen = {
  width: 640,
  height: 480
};

var driver = new Builder()
    .forBrowser('chrome')
    .setChromeOptions(new chrome.Options().headless().windowSize(screen))
    .setFirefoxOptions(new firefox.Options().headless().windowSize(screen))
    .build();

function handleFailure(err, driver) {
     console.error('Something went wrong!\n', err.stack, '\n');
     driver.quit();
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Lucas Azevedo
  • 1,867
  • 22
  • 39
  • 2
    you are missing an await; console.log(await getHTML(url)) – Sodala May 24 '19 at 14:31
  • You are calling your async function outside the async? Why don't work with a then block? Or use await if you really want to have it there.. – Wimanicesir May 24 '19 at 14:31
  • 2
    `console.log(getHTML(url));` just prints the promise created by calling `getHTML`. As with all async functions, to use the return value, use an asynchronous construct. Either `getHTML(url).then(result => console.log(result)).catch(/*...*/)` or `await getHTML(url)` within an `async` function. – T.J. Crowder May 24 '19 at 14:32
  • @Sodala - Not sure that part of the code is in an `async` function. – T.J. Crowder May 24 '19 at 14:32
  • Thanks guys. Issue clarified. – Lucas Azevedo May 24 '19 at 14:35

0 Answers0