0

I want to use Ionic Storage functionality (documented here: https://github.com/ionic-team/ionic-storage ), which is mainly a key/value storage. I am struggeling in regards how to deal with the promises in the best way.

Example: I have created a service to get a storage item by using the key:

  async getFromStorage( lKey: string ){
    return await this._storage.get(lKey);
  }

I am consuming this service in my main component. My aim is to get the value, not the promise. The code above will return the promise and I cannot use await in my main component as it is not async declared.

I tried to do something like that, but it still returns the promise instead of the value:

  /** get saved text from storage */
  getFromStorage( lKey: string ){
    let myvalue = null;
    this._storage.get(lKey).then(
      res => {
          myvalue = res;
      },
      err => {
          myvalue = "";
      }
    )
    return myvalue;
  } 

I know that maybe the scope of myvalue cannot be reached in the res block, but how could I get the value as return value?

Thank you for your help!

CodeThrow
  • 35
  • 1
  • 5
  • 2
    There is no way to get synchronous access to an asynchronous result. You must stick with the promise / async-await pattern. Although `await` gives the impression that you can let the function return the *value*, it actually returns (at the moment of the first `await`) a promise. You have written two wrapper functions around `this._storage.get`, but it will bring you no closer to what that function already provides. – trincot Jun 05 '21 at 11:18
  • Maybe this helps a little: https://stackoverflow.com/questions/21485545/is-there-a-way-to-tell-if-an-es6-promise-is-fulfilled-rejected-resolved – David B. Jun 05 '21 at 11:45

0 Answers0