承诺解决后打字稿返回布尔值
我试图在承诺解决后返回一个布尔值,但打字稿给出错误提示
I'm trying to return a boolean after a promise resolves but typescript gives an error saying
get"访问器必须返回一个值.
我的代码看起来像.
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 code is for Ionic 3 Application and the storage is Ionic Storage instance.
推荐答案
你可以返回一个 Promise
,它会解析成这样的布尔值:
You can return a Promise
that resolves to a boolean like this:
get tokenValid(): Promise<boolean> {
// |
// |----- Note this additional return statement.
// v
return this.storage.get('expires_at')
.then((expiresAt) => {
return Date.now() < expiresAt;
})
.catch((err) => {
return false;
});
}
您问题中的代码只有两个返回语句:一个在 Promise 的 then
处理程序中,一个在其 catch
处理程序中.我们在 tokenValid()
访问器中添加了第三条 return 语句,因为访问器也需要返回一些东西.
The code in your question only has two return statements: one inside the Promise's then
handler and one inside its catch
handler. We added a third return statement inside the tokenValid()
accessor, because the accessor needs to return something too.
这是一个工作示例 在 TypeScript 游乐场:
class StorageManager {
// stub out storage for the demo
private storage = {
get: (prop: string): Promise<any> => {
return Promise.resolve(Date.now() + 86400000);
}
};
get tokenValid(): Promise<boolean> {
return this.storage.get('expires_at')
.then((expiresAt) => {
return Date.now() < expiresAt;
})
.catch((err) => {
return false;
});
}
}
const manager = new StorageManager();
manager.tokenValid.then((result) => {
window.alert(result); // true
});
相关文章