Search code examples
javascriptionic5

How to run through array on Javascript?


I'm stuck retrieving all values from capacitor storage on Ionic 5, I'm retrieving all the time ZoneAwarePromise or Array Iterator, how to deal with it?

Thank you

//MAIN.ts

ngOnInit() {    
    let vaya = this.storage.keys()
    .then(result => {
      return result
    });
    vaya.then(data => {
      for (let item of data) {
        console.log(this.storage.getItem(item))
      }
      
    })
  }

//SERVICE STORAGE.ts

async keys() {
    const { keys } = await Storage.keys();
    console.log('Got keys: ', keys);
    return keys
}

Solution

  • Capacitor Storage is asynchronous so to retrieve all the values it has you need to:

    1. Make sure Capacitor has initialized
    2. Obtain the keys
    3. Write a loop that can do async processing

    This should work (this will retrieve data sequentially):

    ngOnInit() {  
        let values = [];  
        this.storage.keys().then(async (keys) => {
          for (let key of keys) {
            let value = await this.storage.get(key)
            values.push(value)
          };
        });
      }
    

    You can also make the promises run in parallel:

      ngOnInit() {  
        let values = [];  
        this.storage.keys().then(async (keys) => {
          const promises = keys.map(key => this.storage.get(key))
          values = await Promise.all(promises);
        });
      }