如何跳出 JavaScript 循环

How to break out of a JavaScript loop

这是我的功能,我想在满足条件时打破厕所,但出现错误:

SyntaxError: Illegal break statement

我正在使用量角器 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);
  }
};

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

此外,expect 语句是同步的,因此不需要等待,但在使用 Protractor 时,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);
    }
};