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