0

I'm running protractor testing in angularjs application.

let index;

let elm = element.all(by.repeater('registration in myRegistrations'));
elm.getText().then(function(text){
    console.log(text);
    for(var i=0; i<text.length; i++){
        if(text[i] == 'protractor-testing'){
            index = i;
            console.log('Test found :: ' + text[i]);  // get the correct value
        }    
    }

});
console.log("Index :: " + index);  // It says undefined

Here, I get the index result inside if of the for loop function but When I print the index in the console in the last line it says undefined.

How can I get the value of index ?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Virus
  • 303
  • 1
  • 3
  • 10
  • it is `undefined`, your setup is an async flow, so your `undefined` result is completely correct and expected because the inner callback hasn't run yet at that time. Handling it depends on where you need to do what with your index ;) – Icepickle Mar 25 '19 at 20:45
  • You are trying to access a variable before it was initialized. You are using ***asynchronous*** processing. – PM 77-1 Mar 25 '19 at 20:45
  • The `.then` method of a promise stores the handler function and does not invoke it until a future event occurs, e.g. data comes from a server. The `elm.getText()` function does not wait for the server. It immediately returns a promise. The second console.log executes *before* the data arrives from the server. The single thread, non-blocking IO paradigm of JavaScript requires programmers think differently about their code, shifting from imperative programming to [functional programming](https://en.wikipedia.org/wiki/Functional_programming). – georgeawg Mar 25 '19 at 21:29
  • So How can I get the value with Synchronous processing? I'm new so please help me – Virus Mar 25 '19 at 21:33
  • Why can’t you just log the index inside of your if statement in the for loop, right after it was defined? – C. Peck Mar 27 '19 at 12:22

0 Answers0