【发布时间】: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