Storage asynchronous

Hello everybody,

I’m looking for new inputs about my problem with Ionic Storage:

// a bunch of new comment is emitted in same seconde/ms

fromComment.subscribe((newComment) => {

  this.storage.get('comments').then((comments) => {
    console.log("1. Get comments");

    this.comments = JSON.parse(comments) || [ ]; 
    this.comments.unshift(newComment);
    
    this.storage.set('comments', JSON.stringify(this.comments)).then(() => {
      console.log("2. Storage ok");
    });

  }
}

So when I’m receiving comments in a very short period of time, I got problems with asynchronous like :
// 1. Get comments
// 1. Get comments
// 2. Storage ok
// 1. Get comments
// 2. Storage ok
// 2. Storage ok

And the comments in the storage do not match…

Anybody can give me some help please?

You have two options. One would be to create a semaphore to manage concurrent access. A generally better one, if possible, would be to store each comment separately, so they don’t collide. This would be easier if comments have natural unique ids.

All of this presumes that you need to store these comments for offline browsing. If you don’t, stop using storage at all.

1 Like

Thanks for your prompt answer!
I’ll think about all this options.