However, due to the asynchronous nature of promisess, isLoggedIn always return false and the login screen never removed. I’m also aware that I’m nesting promises, which I read is not the best practice. I checked a few links on asynchronous functions and Javascript but I’m still unable to find a solution. Any help is appreciated.
get isLoggedIn(): boolean {
this.ok = false; // you set false here
this.storage.get('user').then(userdata => { // start some asynchronous stuff
this.user = userdata;
this.storage.get('token').then(
tokdata => {
this.tok = tokdata;
if(this.user != null && this.tok != null) {
const body = {user: this.user, token: this.tok, check: 1};
this.http.post(this.loginUrl, body)
.subscribe(data => {
let output = data['output'];
this.ok = (output == 'OK');
return this.ok;
});
}
});
});
return this.ok; // while the asynchronous parts are running, this method continues and returns false
}
You could try something like this. So your function should resolve the promises and return a promise itself, so that you can, wait for it to be finished. That aside I find it really troubling to write unit tests for “get” methods.
Great, thanks for your help. I moved all the isLoggedIn code inside a promise. And now how would I have to reorganize the code or what would I have to do in order to display the login screen if the user is not logged in? Loadiing it inside the promise makes that inothing is displayed: