【问题标题】:Ionic Wait For Function To Finish Before Running Second离子等待函数在第二次运行之前完成
【发布时间】:2020-07-25 11:06:28
【问题描述】:

我的 Ionic App 中有这个功能:

clearTransactions() {
    this.clearIndex = this.clearIndex + 1;
    if (this.clearIndex < 3) {
      console.log("click " + (3 - this.clearIndex) + " more times");
    } else {
      this.storage.clearItems()
      this.storage.getItems().then(
        items => {
          this.items = items
          console.log("test", this.items);
        }
      )
      this.clearIndex = 0;
    }
  }

由于某种原因,this.storage.getItems() 甚至在 this.storage.clearItems() 完成之前运行。任何人都可以为这个问题提出解决方案吗?谢谢!

【问题讨论】:

  • clearItems() 是异步的吗?也许您应该为此提供更多代码,以及为什么假设它在 getItems 之后运行

标签: javascript angular ionic-framework


【解决方案1】:

clearItems 返回一个 Promise,当它像这样完成时,你已经运行了其余的代码:

   this.storage.clearItems().then(()=>{
      // do things after clear
    })

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
  • 我不知道为什么会这样,但确实如此。谢谢!请为未来的读者添加解释。
  • @MartinPascual 添加了描述
猜你喜欢
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多