Working with async behaviour of new Ionic Storage


#1

The new Ionic Storage we have a promise written with ‘get’ method.

// set a key/value
  storage.set('name', 'Max');

  // Or to get a key/value pair
  storage.get('age').then((val) => {
    console.log('Your age is', val);
  });

Which is hard when we writing code with promises since it’s async behavior. Anybody came up with any suggestions for handling this. I thought of using new async/await. Will it be good?


#2

What is hard about this?
What problems are you encountering?


#3

Matter of opinion, but mine is “no”. async/await obscures the asynchronous nature of operations, which I find reduces code clarity. It also encourages ignoring errors.


#4

the async/await syntax is more clear than the callback hell in promise.

you can wrape the storage.get in a function like this

async getKey(key:string): Promise<void>{
  return await storage.get(key);
}

now you can call the function which will return the specfied key value

console.log(getKey("someKey"));

#5

What callback hell are you referring to?


#6

You can consider using decorators

I won’t though.

Regards

Tom


#8

This is exactly what I am trying to achieve.
But for I don’t know what reason, it breaks my app -> it loads with blank page only.
When I comment my method, it works again.
Here is my code:

async getApiTokenAsync(): Promise<void> {
  return await this.storage.get('bearer');
}

Any suggestion ?

Edit:
I resolved my problem.
it was a matter of typescript version. The async/await functionnalities were integrated since version 2.1