【问题标题】:How to handle a Promise in a Loop如何在循环中处理 Promise
【发布时间】:2021-07-14 19:33:25
【问题描述】:

下面有一段代码:

browser.sleep(2000).then(function(){
  element.all(by.xpath('one xpath')).then(function(elements){
   for(let elm of elements){
     elm.getText().then(function(text){
      if(text == "ButtonA"){
        elm.click();
      }
    })
   }
 })
});

funcB();

funcB()elm.click() 之前执行 我知道,我在 for 循环中使用了 Promise。它会出错。而且我已经尝试了一些我在互联网上找到的解决方案,但到目前为止我还没有找到如何让elm.click()funcB 运行之前工作。请帮忙!

【问题讨论】:

  • Promise.all(element.all...).then(() => funcB()) 应该可以工作。
  • elem.click() 可能它自己执行异步工作 - 您是否希望等待异步工作完成?此外,我们不知道 elem 到底是什么(可能是一个 HTML 按钮?)以及它是否支持 Promises 或回调以在完成时进行通知
  • @Jamiec: 元素 = [Button, ButtonA, ButtonB, ButtonC, ButtonD]。我想先找到ButtonA,然后点击ButtonA,最后运行funcB()
  • 所以...把它放在循环之后。我不明白这种混乱。
  • 我想每个人刚开始的时候都有这个问题。至少我也是。我不知道为什么所有这些反对票不断涌现

标签: javascript loops promise protractor


【解决方案1】:

如果你像这样使用async/await而不是.then,你会惊讶于小学生可以使用量角器

it('test case', async () => {
  await browser.sleep(2000)
  let elementArrayName = element.all(by.xpath('one xpath'));
  for (let i = 0; i<await elementArrayName.count(); i++) {
    let text = await elementArrayName.get(i).getText();
    if(text === "ButtonA"){
      await elementArrayName.get(i).click();
    }
  }

  // IMPORTANT!
  // I don't know what your funcB is, 
  // but I have a feeling it returns a promise and thus needs await too
  await funcB();
});

你现在觉得你的代码怎么样?

所以.thenawait 都指示javascript 停止,直到promise 得到解决,但第二个不需要你构建这些无穷无尽的胡夫金字塔并保持简单、可读和可调试

【讨论】:

  • @MusterTester 让我知道这是否适合您
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-24
  • 2018-06-08
  • 2018-03-26
  • 2017-07-26
  • 2020-08-26
相关资源
最近更新 更多