my Logged_user value is ‘9715328568’ which is taking from the local storage
if (this.logged_user ==undefined){
this.storage.get('username').then((auth) => {
this.logged_user=auth;
console.log(this.logged_user,' is already logged in '); //---- result '9715328568,' is already logged in '
});
console.log(this.logged_user,' is already logged in signup screen'); //-- result undefined is already logged in signup screen
}else{
this.logged_user=this.logged_user
}
Outside of promise its shwing as indefined …
“console.log(this.logged_user,’ is already logged in signup screen’); //-- result undefined is already logged in signup screen”
Promise is an asynchronous method. In your case you call this.storage.get which returns a Promise. This means the value is only available when the Promise has fulfilled.
Your console.log() after the then method the Promise shows a value of this.logged_user which is called after the Promise is fulfilled. The value this.logged_user is undefined because the Promise is not completed.
The value is only available in the then method of the Promise. All further handling of this.logged_user depends on the Promise resolved value.
If you want a clean sync-like code with Promises, I recommend to async-await.
class YourClass {
public logged_user: string;
public async login() {
if (this.logged_user !== undefined) {
console.log('User is already set.');
return;
}
console.log('logged_user is ', this.logged_user);
// Expected Result: Undefined (ok)
// The value of the resolved Promise is set to this.logged_user.
// It waits until the Promise is fulfilled. (Does not block the rest of your code. Don't worry.)
this.logged_user = await this.storage.get('username');
console.log(this.logged_user, ' is already logged in ');
// Result: '9715328568,' is already logged in.
console.log(this.logged_user, ' is already logged in signup screen');
// Result: '9715328568' is already logged in signup screen.
}
}
Look out for async before the method / function name and await before Promise. Note: Your method login is now a Promise, too.