【问题标题】:TypeScript Promise Function IssueTypeScript Promise 函数问题
【发布时间】:2017-02-17 19:21:23
【问题描述】:

我正在尝试检查是否存在本地存储的数据并相应地显示/隐藏部分视图。我通过将 true 或 false 分配给 formMarkersDisplay 来做到这一点,如下所示:

ionViewWillEnter() {
  this.formMarkersDisplay = this.dataService.isNearMiss(this.appGlobal.getReportPrimaryKey());
}

这里是isNearMiss函数:

isNearMiss(pk) {
    let sectionSevenObj : any;
    this.getReport(pk).then((report) => {
        if (report) {
            sectionSevenObj = JSON.parse(report);
            sectionSevenObj = sectionSevenObj.report.sections.section7;
            if(Object.keys(sectionSevenObj).length != 0) {
                this.is_markers = true;
            } else {
                this.is_markers = false;
            }
        }
    });
    return this.is_markers;
}

这里是getReport:

getReport(pk) {
  return this.storage.get(pk);
}

问题是 this.is_markers 被设置为 false ,即使我期望为 true (显示在 console.log 中)。我一直在努力让自己的头脑与 Promises 一起工作。我认为这可能与此有关。

如何修改我的代码以使其正常工作?

【问题讨论】:

  • 你需要返回承诺,而不是它变异的变量
  • 您的代码中还有其他问题。例如,这一行的类型注释不仅没有意义,而且实际上阻止了 TypeScript 捕捉错误let sectionSevenObj : any;。鉴于您正在做一些奇怪的事情,例如从同一对象上的方法返回绑定到 this 的值,您似乎需要复习 JavaScript 基础知识
  • 我对 JS/TS 很陌生。我该如何兑现承诺?我正在寻找对我的代码进行实际修订的一些示例,以指出我正确的方向。
  • 我稍后会尝试为您写一些东西,但严重的是,您在短短几行中就有很多错误。就像分配给一个变量而不是读取它的结果然后分配给其他东西。这些基本上都是错误,与 JavaScript 或 Promise 无关。我并不是要劝阻你,但你应该从基础开始。不要从像 ionic 这样的复杂框架开始,而是学习语言的基础知识
  • 谢谢。我一直在尝试很多事情来让它发挥作用,所以不足为奇。如果你能在这里看看如何回报承诺,我会很高兴。

标签: typescript promise ionic2


【解决方案1】:

是的,您可以使用承诺。您的代码中的问题是它是非阻塞的,因此当您输入 this.getReport() 时它会执行,然后沿着它返回 this.is_makers 及其声明的初始状态,它不会等待 this.getReport() 完成。

对于使用 Promise,您可以这样做:

isNearMiss = (pk: any): Promise<boolean> => {
  return new Promise<boolean>(ret => { //RET VAR IT'LL RETURN IN CASE OF SUCCESS
    let sectionSevenObj : any;
    this.getReport(pk).then((report) => {
      if (report) {
        sectionSevenObj = JSON.parse(report);
        sectionSevenObj = sectionSevenObj.report.sections.section7;
        if(Object.keys(sectionSevenObj).length != 0) {
            ret(true); // it'll return true
        } else {
            ret(false);
        }
      }
    });
  })
}

并修改你的ionViewWillEnter

ionViewWillEnter() {
  this.dataService.isNearMiss(this.appGlobal.getReportPrimaryKey()).then(ret =>{
    // DO THE CODE IF RET IS TRUE OR FALSE, LIKE SETING this.formMarkersDisplay = ret;
  });
}

【讨论】:

  • 这太完美了!万分感谢!我理解了这个问题,但很难正确使用语法。
猜你喜欢
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 2021-01-09
  • 2019-10-26
  • 2020-03-25
  • 1970-01-01
  • 2021-08-29
  • 2019-08-29
相关资源
最近更新 更多