Skip to content Skip to sidebar Skip to footer

Unable To Get The Length

I am novice to javascript concepts. Why i am getting the different output for the same variable length? While it is showing the expected result inside the body ? var length; elemen

Solution 1:

Because your all() is async call so console.log will run before you finish then chain and assign value to length

Solution 2:

The element.all(by.className("className")).getText()) call in your function returns something called a promise- it executes some code, and after this code is executed, it calls the function inside .then(). However, this happens independently of the rest of your program- so it continues to execute the console.log after the .then() statement.

This leads to what is called a race condition- where the order of operations can be undefined.

Solution 3:

All before answers already explain what happens and why. So it's clear, that your 3rd console.log is executed before your then() condition finishes.

What you can try is this:

var length;
element.all(by.className("className")).getText().then(function(items){
    length = items.length;
    console.log("1st output = "+length);//1console.log("2nd output = "+items.length);//1
});
browser.waitForAngular();  //add this line to let Protractor wait for Async tasks to be resolved firstconsole.log("3rd output = "+length);

However, keeping the 3rd console.log() inside the then() statement would be the more proper solution.

Post a Comment for "Unable To Get The Length"