I want to get a boolean value from a promise.
Method One
get tokenValid(): Promise<Boolean> {
return new Promise((resolve, reject) => {
this.storage.get('expiresAt')
.then((expiresAt) => {
resolve(Date.now() < expiresAt);
})
.catch((err) => {
reject(false);
});
});
}
Method Two
get tokenValid(): Promise<Boolean> {
return new Promise((resolve, reject) => {
this.storage.get('expiresAt')
.then((expiresAt) => {
resolve(Date.now() < expiresAt);
return Promise.resolve(true); // difference is here
})
.catch((err) => {
reject(false);
return Promise.reject(false); // difference is here
});
});
}
One and two are similar. The difference is in method Two there is the return statement either true or false. To get the value, just call the method as
if(this.tokenValid()) {
console.log('return true');
} else {
console.log('return false');
}
UPDATE:
By the comments, I modified the methods as
Method Three
get tokenValid(): Promise<Boolean>() => new Promise((resolve, reject){
this.storage.get('expiresAt')
.then((expiresAt) => {
resolve(Date.now() < expiresAt);
})
.catch((err) => {
reject(false);
});
}
To get the value, just call the method as
if(this.tokenValid()) {
console.log('return true');
} else {
console.log('return false');
}
I understand I have to use .then()
. But why my method always return true?