【问题标题】:How to get the value of a promise in an async / await function on typescript?如何在打字稿的异步/等待函数中获取承诺的价值?
【发布时间】:2017-06-29 10:55:55
【问题描述】:

我有以下代码:

export class AuthService {

  private key:string = "";

  constructor(private storage: Storage) {

  }

  private async getKey() {
    let response = await this.storage.get('key');
    return response;
  }

  public init() {
    this.key = this.getKey();
  }
}

但我收到以下错误:type promise any is not assignable to type string,问题出在 getKey() 的返回上。

我想将 this.key 的值设置为存储在 Storage 中的值,我知道我可以使用:

this.storage.get('key').then((val) => { this.key = val });

但我想以同步方式进行。

非常感谢

【问题讨论】:

  • init 不是一个异步函数,所以你不能像在getKey 中那样在await 中作出承诺。不,不可能立即(同步)获得承诺的结果值,async functions 不会改变这一点。

标签: typescript ionic-framework promise es6-promise


【解决方案1】:

key 是一个字符串。 getKey 和所有 async 函数的返回值是一个承诺。正如 TypeScript 告诉你的那样,你不能将承诺分配给字符串。相反,您必须等待承诺(使用then)并将承诺的值分配给key。所以:

export class AuthService {

  private key:string = "";

  constructor(private storage: Storage) {

  }

  private async getKey() {
    let response = await this.storage.get('key');
    return response;
  }

  public init() {
    this.getKey().then(key => this.key = key);
  }
}

或者,您可以将 init 本身设为异步函数:

public async init() {
  this.key = await this.getKey();
}

当然,this.keythis.getKey() 解析之前仍不会被填充,而在this.storage.get 解析之前不会填充。

在许多情况下,最好直接在模板中“解包”promise,使用async 管道:

export class AuthService {

  public key: Promise<string>;

  constructor(private storage: Storage) { }

  ngOnInit() { this.key = this.storage.get('key'); }
}

// template

The key is {{key | async}}

但我想以同步方式进行。

你不能。除了时间机器之外,没有办法将异步的东西变成同步的东西。如果将来有什么事情要发生——无论是 100 毫秒,还是 100 年——你必须等待它。无论您等待promise.then()await 的承诺,都是如此。 await 不会神奇地将未来转变为现在。它只是一种语法糖,允许您以看起来同步的方式编写代码,后续逻辑直接位于 await 之后,而不是在 then 处理程序中。

【讨论】:

  • 感谢您的回答,一些问题和疑问:我不使用模板上的值,所以我不能使用async 管道。湾。如果 await 仍然返回一个 promise,那么使用它的目的是什么。
  • 如果你有一个承诺,无论如何你都必须等待它。 await 只是一种语法,它允许您等待它并根据需要分配它的值。 await a = promise(); ... 完全等同于 promise.then(a =&gt; ...)。它本质上是语法糖。 await 无法将异步变为同步。什么都做不到。
猜你喜欢
  • 1970-01-01
  • 2019-03-18
  • 2022-01-22
  • 2018-02-03
  • 2018-05-03
  • 1970-01-01
  • 2017-12-01
  • 2016-05-22
  • 2020-11-19
相关资源
最近更新 更多