【问题标题】:Using Async and Await in Ionic3 and angular4在 Ionic3 和 angular4 中使用 Async 和 Await
【发布时间】:2017-07-14 00:51:33
【问题描述】:

我们从未使用过 await/async,所以这个问题也可能是一个愚蠢的问题,但我们有什么问题?

这是我们的代码:

  constructor() {
       let text = this.textAsync();
       console.log('text: ', text);
  }


  async textAsync() {
    let val = await this._text(); 
    return val;
  }

  _text(): Promise<any> {
    return new Promise((resolve, reject) => {
           resolve('TEEEEXXTTTTT');
    })
  }

日志从来不是text: TEEEEXXTTTTT,而是类似的东西

text: ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array[0]}

我确定有一个简单的解决方案:微笑:

谢谢

【问题讨论】:

    标签: angular asynchronous ionic-framework async-await


    【解决方案1】:

    this.textAsync(); 返回一个承诺,所以你必须等到它解决:

      constructor() {
           this.textAsync()
           .then((text)=> { console.log('text: ', text) });
      }
    

    【讨论】:

    • 但是如果我看到这个例子joshmorony.com/using-asyncawait-syntax-for-promises-in-ionicgetFromStorageAsync 也在做同样的事情并且他没有打电话。那么......我真的很困惑:o,你可以分享一个 plnkr 吗?
    • 当然,这里是the plunkerasync functions 返回一个承诺。您可以跳过使用then,但在这种情况下,您将获得对promise 的引用,就像您在ZoneAwarePromise 中一样,而不是promise 解析的结果。你在文章中提到他不使用的地方在哪里?
    • @MichaelBurger,嘿,我的回答有帮助吗?
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 2019-01-29
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多