I have the following code. I'm relativly new to protractor & JavaScript so apologies if this is a stupid question but I have done a lot of research with no luck. All I'm trying to do is select an option from a drop down until a certain button appears. All my code works but when I put it into a while loop it doesn't do anything. Can anyone explain why this is happening? I know it's something to do with the way it's asynchronous but I'm self thought and can't figure this one out. Thanks in advance.
function selectProject(i){
var selectSecondProject = element(by.id('translation-brief--select-project')).all(by.tagName('option')).get(i);
selectSecondProject.click().then(function() {
browser.sleep(2000);
});
};
it('should select a different project from the drop down menu', function(){
var loop = true;
var i = 1;
while(loop == true){
selectProject(i).then(function(){
browser.sleep(2000);
});
element(by.id('brief-button')).isDisplayed().then(function (isVisible) {
if (isVisible) {
loop = false;
}
else{
i++;
}
});
}
答案 0 :(得分:1)
The sleep
function is executed asynchronously, so it's not really happening inside the timing of the loop. In fact, the loop should likely go on forever, never giving the then
function, along with the sleep
, a chance to ever execute.
The way to make a loop function asynchronously is to either use setInterval
or setTimeout
to restart the loop. I can go into that in more detail if it isn't clear.
Update:
Here's a rough idea of what I'd suggest (I haven't actually tested this code, so beware. It's just a rough idea!):
it('should select a different project from the drop down menu', function(){
var i = 1;
function myLoop () {
selectProject(i).then(function(){
browser.sleep(2000);
element(by.id('brief-button')).isDisplayed().then(function (isVisible) {
if (!isVisible) {
i++;
setTimeout(myLoop);
}
});
})
}
myLoop();
});