从Promise块返回函数中的值 [英] Return value in function from a promise block
问题描述
我正在尝试编写一个函数(使用WebdriverJS lib),该函数遍历元素列表,检查名称并构建与该名称相对应的xpath定位器.我在这里简化了xpath定位器,所以不用注意.
我在这里面临的问题是: 1)调用此函数将返回未定义.据我了解,这是因为return语句不在其位置,而是: 2)将其放置在同步代码通常可以正常工作的正确位置,不适用于异步承诺,因此调用此函数将返回相同的未定义,但是因为return语句在"driver.findElement"语句之前触发. /p>
如果由于调用此函数而要获取createdTask变量,该如何在此处使用return语句?
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;
}
});
}
});
};
您可以首先使用promise.map
获取所有文本,然后使用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 + "]";
});
}
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 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 + "]";
});
}
这篇关于从Promise块返回函数中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!