如何摆脱JavaScript循环

问题描述 投票:0回答:1

这是我的功能,当条件满足时我想中断厕所,但出现错误:

SyntaxError:非法中断语句

我使用带有javascript的量角器。

async CompareTableData(byElement, param) {
  try {
    await this.WaitToBeClickable(element(By.cssContainingText(byElement.value, param)));
    await element.all(byElement).then(async function(item) {
      for (var i = 0; i < item.length; i++) {
        item[i].getText().then(async function(text) {
          var trimTxt = text.trim();
          if (await trimTxt == param && byElement.using == "css selector") {
            console.log(`Param FOUND! ${param}\n`);
            await expect(element(By.cssContainingText(byElement.value, param)).isPresent()).toBe(true);
            break;
          } else {
            return;
          }
        });
      }
    });
  } catch (err) {
    console.log("Table comparison FAILED, element not present!");
    return console.log(err);
  }
};
javascript selenium protractor
1个回答
0
投票

正如其他人指出的那样,中断不是在循环中,而是在.then中的匿名函数中。除此之外,主要问题是您没有很好地履行诺言。引入Async/await是为了简化承诺,因为它不需要您使用.then语句,因此您绝对不应该以这种方式一起使用它们。

expect语句是同步的,因此不需要等待,但是使用量角器时,期望中的动作(几乎总是)将是异步的,因此该语句应读取为expect(await element(By.cssContainingText(byElement.value, param)).isPresent()).toBe(true);

您可以这样重写代码:

async function CompareTableData(byElement, param) {
    try {
        await this.WaitToBeClickable(element(By.cssContainingText(byElement.value, param)));
        const item = await element.all(byElement)

        for (var i = 0; i < item.length; i++) {
            const text = await item[i].getText();
            var trimTxt = text.trim();
            if (trimTxt == param && byElement.using == "css selector") {
                console.log(`Param FOUND! ${param}\n`);
                expect(await element(By.cssContainingText(byElement.value, param)).isPresent()).toBe(true);
                break;
            } else {
                return;
            }
        }
    } catch (err) {
        console.log("Table comparison FAILED, element not present!");
        return console.log(err);
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.