Ionic Storage and Promise : always empty


#1

Hello,

I want to get an expiration date of a jwt token from ionic storage. I can’t get the expiration value outside the promise.

public isLoggedIn() {
return moment().isBefore(this.getExpiration());
}

public getExpiration() {
if(!this.getToken()) {
return;
}
let expiration = null
this.storage.get(‘token’).then((token) => {
expiration = helper.getTokenExpirationDate(token); <— here expiration is not equal to null
})

  return expiration; <---- alway equal to null

}

I need to do this with ionic storage, not localStorage.
Any tips ?


#2

This is an unavoidable consequence of how Promises work. getExpiration must be redeclared to return Promise<Date>, and its callers must deal with that. For instance, isLoggedIn has to return Promise<boolean>.


#3

Can you be more specific ? I searched example on google but I can’t find anything.
I can’t find a use of ionic storage with promise. The examples given by ionic are pretty poor https://ionicframework.com/docs/storage/
How can I set the value of this.expiration globally if the result is always in a promise ?
Here I found another simple example : https://github.com/ghadeer-io/ionic-3-local-storage-example/blob/master/src/pages/home/home.ts : In every example, ppl are dumping the content of the ionic storage inside the promise to show the result, but how to set this result to use it later, outside the promise ?
Thanks


#4

Nobody can advise me ?

I managed to make it work with your advices thanks