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;
});
}
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.
Here is a working example in the TypeScript playground:
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
});
Promise<boolean>
by just returningthis.storage.get...
though. – DisquietingtokenValid
is causing side effects. Can you provide more details. – Weakfishget
. – Ceibaasync
/await
syntax only is sugar forthen
calls - it's still asynchronous and returns a promise. – Ceiba