I do something very close to what is shown in your S.O. example, but maybe I do even more.
I basically read the storages not only in the main thread, but also in EVERY chrome event handler (especially the runtime.onMessage event).
This is because events can be triggered not only when SW is asleep but also when it is already awake.
But that's not enough for me; If I see the promise relating to the storage reading is pending, I wait for it to be completed and I don't take its output, but I read the storage again.
> This is because I'm not sure that during the pending read, in any part of the code (main thread or event handler) the storage hasn't changed in the meantime. <
( @Stefan in his
answer states that it would suffice to create a new promise, wrap the storage writing method inside it and "await" that promise to be sure that the writing is completed before any other chrome API event can occur.
PLEASE, someone convince me of this, because I have STRONG DOUBTS. )
In any case, I wait for the previous promise (if any) to fulfill otherwise the new instance of my read-and-write-in-cache procedure would risk destroying the already created cache object.
I'm still in the process of migrating (and testing at the same time) so only time will tell me right or wrong.
I'm trying to find a compromise between writing as little code as possible (but easily readable code) and writing pitfall-proof code.
Exchanging messages to the SW is a technique I'm already doing when I change items of crucial importance for the extension. I send a message and on the other side I read the storage again.
However, if I modify a single storage item (item(s) of secondary importance), I would tend not to exchange a message, also because it would all become a "chitchat", which seems impractical and also inelegant to me.
But maybe I should focus more on building a system that
LOCKS STORAGE AT THE WRITE STAGE and then releases it when it's done.
I could do this with a globally accessible promise that I create when I go to write to the storages and that I check during the subsequent read.
So when the event fires and I go to read the storage I ask myself: "
Is there a write in progress? If so, wait for its conclusion and then read, otherwise read immediately."
Alternatively, if I don't want to use a promise, I could approach using this Web lock API which looks promising to me.
I could perhaps place an exclusive lock on the storage resource so that this resource is not read when it is written.