【问题标题】:How to remove the setTimeout and use async await method in angular如何删除 setTimeout 并在角度中使用异步等待方法
【发布时间】:2020-09-18 13:36:14
【问题描述】:

如果我从下面提到的代码中删除了setTimeout,则代码块 (getUnderlyingData) 会在上一个响应之前运行。所以我没有得到正确的回应。请任何人帮助我解决这个问题。 当前代码:

await this.TableauService.initViz(this.TableauViz, this.DataContainer, this.DataURL).then(([uniqData, TableauViz]) => {
    this.VizWorkbook = TableauViz;
    setTimeout(() => {
      this.SheetData = this.TableauService.getUnderlyingData(TableauViz, "KPI",(response) => {
        console.log("sheet data",response);
      }); 
    },7000);
  });
}

【问题讨论】:

  • 首先,混合使用async/await 和.then 几乎总是错误的。其次,为超时创建一个助手const delay = async ms => new Promise(resolve => setTimeout(resolve, ms));。这是直接使用 Promise 构造函数的罕见 案例之一,当您调整基于回调的 API(如 setTimeout)时。用法:await delay(7000)

标签: javascript async-await es6-promise


【解决方案1】:

或者您可以简单地将这一行 this.VizWorkbook = TableauViz; 添加到您的 getUnderlyingData(.. { this.VizWorkbook = TableauViz; ... } 中

【讨论】:

    【解决方案2】:

    如果您使用await,则无需使用then 来解决promise,await 将为您完成。

    异步函数可以包含一个 await 表达式,该表达式暂停异步函数的执行并等待传递的 Promise 的解析,之后它会恢复异步函数的执行并返回解析的值。

    async functionName(){
    let result = await this.TableauService.initViz(this.TableauViz, this.DataContainer, this.DataURL)
    }
    

    上面的result 变量保存了你的解析值,你可以做任何你想做的事情。

    【讨论】:

      猜你喜欢
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 2017-01-05
      相关资源
      最近更新 更多