【发布时间】:2018-01-21 15:38:09
【问题描述】:
我试图在 promise 解决后返回一个布尔值,但 typescript 给出错误提示
A 'get' accessor must return a value.
我的代码看起来像。
get tokenValid(): boolean {
// Check if current time is past access token's expiration
this.storage.get('expires_at').then((expiresAt) => {
return Date.now() < expiresAt;
}).catch((err) => { return false });
}
此代码用于 Ionic 3 应用程序,存储为 Ionic Storage 实例。
【问题讨论】:
-
你不能这样做......你可以通过返回
this.storage.get...来返回Promise<boolean>。 -
你可能不应该对有副作用的东西使用吸气剂。
-
@ShaunLuttin 是的,这是更准确的描述。我使用“副作用”是因为 a)时间通常被认为是一个 b)我们确实不知道查询的作用(并且“发送请求”可能是一种改变各种东西的动作,至少在较低的水平)。
-
@user2473015 不,当它是异步的时,它必须返回一个布尔值的承诺。要使其成为一种方法,只需省略
get。 -
@user2473015 不,不可能让它同步。使用
async/await语法只是then调用的糖 - 它仍然是异步的并返回一个承诺。
标签: javascript typescript es6-promise ionic3 ionic-storage