Wednesday, April 3, 2019

node.js - Return value in function from a promise block



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;
}
});
}
});

};

Answer



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 + "]";
});
}

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...