0

Code 1

resultsBoard.findElements(By.css(mySelector)).then(function(elements) {
  elements.forEach(function(val, idx) {
    elements[idx].getText().then(function(text) {
        console.log(text);
    });
  });
});

Code 2

resultsBoard.findElements(By.css('mySelector')).then(function(elements) {
  for (var idx = 0; idx < elements.length; idx++) {
    elements[idx].getText().then(printText(text));
  }
});

Code 1 works well and retrieves the text of all the elements that matched my selector. Code 2 gives me a

ReferenceError: text is not defined

What is the difference? Why does this happen?

Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53

2 Answers2

2

The 2nd snippet adds calling parenthesis that invoke the function (printText) immediately, expecting text to already be defined. These parenthesis aren't present in the 1st snippet.

elements[idx].getText().then(printText(text));

// is equivalent to...

var _result = printText(text);
elements[idx].getText().then(_result);

To provide a named function as an argument, you'll want to just use its name as a variable:

elements[idx].getText().then(printText);
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • It is perfectly clear now. My JSHint Gutter was telling me to create a function outside and i ignored that printText function. I was expecting the difference to come from the forEach. Thanks – Tiago Bértolo May 07 '16 at 19:21
1

In the first example:

elements[idx].getText().then(function(text) {
   console.log(text);
});

The .then(function(text)) part is actually giving a name (text) to the data that you get from getText(), so you can use it in the next line. You are not doing this in the second example.

So you should rewrite your second example to something like this to get it to work:

resultsBoard.findElements(By.css('mySelector')).then(function(elements) {
  for (var idx = 0; idx < elements.length; idx++) {
    elements[idx].getText().then(function(text) {
      printText(text);
    });
  }
});
MunchyYDL
  • 351
  • 1
  • 5