javascript - 有 2 个相同的接收值来自一个 Promise:在一种情况下它可以工作,在另一种情况下它给出一个 TypeError: x is not a function
问题描述
我在自动测试中使用元素搜索并从列表中获取名称。我的代码有效,一切都很好。但在自动测试中,我多次使用此代码。因此,我决定将其放入一个函数中,并在需要时调用它。代码运行:
await driver.wait(until.elementLocated(By.className("item")), 20000);
let findItems1 = await driver.findElements(By.className("item"));
let items1 = findItems1.map(async elem => await elem.getText());
await Promise.all(items1);
let currentItem1 = findItems1[findItems1.length - 1];
await currentItem1.click();
currentName = await currentItem1.getText(); // This string operates
await Promise.all(currentName)
console.log(currentName)
我从 promise 所在的函数推断变量的值。我可以点击这个项目。但是当我想从 promise 中获取文本值时,字符串“currentName = await currentItem1.getText()”会引发错误。尽管在我的第一个代码中,这一行有效。我不明白可能是什么原因。
代码不运行:
async function findCurrentItem(){
await driver.wait(until.elementLocated(By.className("item")), 20000);
let findItems = await driver.findElements(By.className("item"));
let items = findItems.map(async elem => await elem.getText());
await Promise.all(items);
let currentItem = findItems[findItems.length - 1];
return currentItem;
}
let current = findCurrentItem();
await currentItem1.click();
console.log(current, 1) // console displays promise
let currentName = await current.getText(); // This string doesn't operate
await Promise.all(currentName)
console.log(currentName, 2) // console displays error
错误:
TypeError: currentItem.getText is not a function
我能做些什么?
解决方案
您创建了 findCurrentItem 异步函数,但在使用它时不要等待它的结果。改成let current = await findCurrentItem();
推荐阅读
- php - Ajax 请求返回“mysqli_stmt_execute(): Property access is not allowed”
- sql - 如何在 PostgreSql 中明智地获取特定的随机记录组合
- powershell - Exclude one folder and a filetype from Get-childitem
- python - 无法使用键 lambda 函数对 csv 文件进行排序
- r - Traminer:具有观察次数的平均时间条形图
- tomcat - 由于循环继承依赖,tomcat启动抛出stackoverflowerror
- android - 如何使用回调对挂起函数进行单元测试
- python - 从 Python 中的子文件夹导入本地模块时出现 ModuleNotFoundError
- javascript - 底部子项展开时向下滚动父容器
- python - Pywinauto 控制/连接到像弹出窗口一样的窗口