首页 > 解决方案 > 有 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

我能做些什么?

标签: javascriptnode.jsseleniumselenium-webdriver

解决方案


您创建了 findCurrentItem 异步函数,但在使用它时不要等待它的结果。改成let current = await findCurrentItem();


推荐阅读