Return value in function from a promise block

0
0

I’m trying to write a function (using WebdriverJS lib) that iterates through a list of elements, checks the names and build an xpath locator that corresponds to that name. I simplified xpath locators here, so don’t pay attention.

The issues I’m facing here are:
1) Calling this function returns undefined. As far as I understand, this is because the return statement is not in its place, but:
2) Placing it in the correct place where a synchronous code would normally work, doesn’t work for async promises, hence calling this function will return the same undefined, but because the return statement fires before the “driver.findElement” statement.

How should I use the return statement here, if I want to get createdTask variable as a result of calling this function?

var findCreatedTask = function() {
var createdTask;
driver
.findElements(By.xpath("//div[@id='Tasks_Tab']")).then(function(tasks) {
for (var index = 1; index <= tasks.length; index++) {
driver
.findElement(By.xpath("//div[@id='Tasks_Tab'][" + index + "]//div[@class='task-title']")).getText().then(function(taskTitle) {
if (taskTitle == "testName") {
createdTask
= "//div[@id='Tasks_Tab'][" + index + "]";
return createdTask;
}
});
}
});
};
  • You must to post comments
0
0

You could first get all the texts with promise.map and then get the position with indexOf :

var map = webdriver.promise.map;
var findCreatedTask = function() {
var elems = driver.findElements(By.xpath("//div[@id='Tasks_Tab']//div[@class='task-title']"));
return map(elems, elem => elem.getText()).then(titles => {
var position = titles.indexOf("testName") + 1;
return "//div[@id='Tasks_Tab'][" + position + "]";
});
}
  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website