Search code examples
javascriptangularionic5

Ionic Data Storage wait for a promise to finish


I am using Data Storage from Ionic Framework. In my code, I have my auth guard which checks user info is stored or not. Code is :

this.storage.get('user_info').then((data) => {
  let user_info = JSON.parse(data);
  if(user_info == null)
  {
    this._userIsLoggedIn = false;

  } else {

    this._userIsLoggedIn = user_info.isLogin;

  }
});

return this._userIsLoggedIn;

I am only getting the default value that I set. How do I wait for the promise to finish before it is returning?


Solution

  • If you using promises in a method and want to return the result of the promise, you should also promisify your method too. You can achieve this in two way:

    1. Return a promise
    2. Or use async-await

    Approach 1 :

    return new Promise( resolve => {
    this.storage.get('user_info').then((data) => {
      let user_info = JSON.parse(data);
      if(user_info == null)
      {
        this._userIsLoggedIn = false;
    
      } else {
    
        this._userIsLoggedIn = user_info.isLogin;
      }
    
      return resolve(this._userIsLoggedIn);
    });
    
    });
    

    Approach 2 (Which is cleaner):

     const data = await this.storage.get('user_info');
      let user_info = JSON.parse(data);
      if(user_info == null)
      {
        this._userIsLoggedIn = false;
    
      } else {
        this._userIsLoggedIn = user_info.isLogin;
      }
    
    return this._userIsLoggedIn;
    

    Also, note that you should modify your function with async keyword in order to use await.