我有以下代码:
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的值设置为存储在存储上的值,我知道我可以使用:
this.storage.get('key').then((val) => { this.key = val });
但我想以同步的方式做到这一点。
非常感谢
答案 0 :(得分: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.key
在this.getKey()
结算之前仍然不会填充this.storage.get
,直到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}}
管道直接在模板中“解包”承诺:
promise.then()
但我想以同步的方式做到这一点。
你做不到。除了时间机器之外,没有办法让异步成为同步的东西。如果将来会发生一些事情 - 无论是100毫秒还是100年 - 你必须等待它。无论您是等待await
还是await
的承诺,都是如此。 await
并没有神奇地将未来变为现在。它只是语法糖,允许您以外观同步的方式编写代码,后续逻辑直接在then
之后,而不是{{1}内部处理程序。