Ionic 3 method not pushing to array

Hi, I’m trying to push data into an array and for some reason it produces a void. This is the method:

getAllFavorites() {
  let items = [];

  console.log('Getting all favs...')
  this.storage.ready().then(() => {
     this.storage.forEach( (v, k) => {
        items.push(JSON.parse(v));
        console.log(JSON.parse(v))
     });
  });

 return items.length ? items : null;

}

and then on:
onViewDidEnter() {
this.favorites = this.userSettings.getAllFavorites();
console.log("Favs: ", this.favorites);
}

During the forEach callback, It prints out fine but the push method does nothing. Calling the getAllFavorites returns null or a void/undefined if I return the items array directly. What am I doing wrong?

You’re checking the value of this.favorites before the Promise completes.

I don’t think that is it. I just printed the length of the items array after the forEach method and it returned: 0

this.storage.ready().then(() => {
     this.storage.forEach( (v, k) => {
        items.push(JSON.parse(v));
        console.log(JSON.parse(v))
     });
     console.log("length:  ",items.length);
});

Alrighty, so. Promises.

Promises are asynchronous. Which in short means it finishes at some point. It may finish now. It may finish 5 years from now. We’re not sure though.

In your code you have:

this.storage.ready().then(() => {
//..my code here
});

This says, hey, storage. Whenever you’re ready, lemme know so that I can execute //..my code here.

This is great! However, that means it probably hasn’t executed when you get to the line

return items.length ? items : null;

Why? Because it’s a promise. It’ll get back to you, it promises!, but not yet.

So! How do we fix this?

You’ll have to change getAllFavorites to something like this:

getAllFavorites() {
  console.log('Getting all favs...')
  return this.storage.ready().then(() => {
     let items = [];

     this.storage.forEach( (v, k) => {
        items.push(JSON.parse(v));
        console.log(JSON.parse(v))
     });

     return items.length ? items : null;
  });
}

Then, you’ll have to change ionViewDidEnter to:

ionViewDidEnter() {
    this.userSettings.getAllFavorites(faves => {
        this.favorites = faves;
        console.log("Favs: ", this.favorites);
    });
}
1 Like

Ahhhh, ok. It is the async timing thingy. I come from the c++ world and this async programming still throws me off. Thank you. That makes complete sense.