简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM