How to get the LocalStorage value out of promise scope

A couple of things.

Exposing the object as a Promise instead of a raw Preferences means we can get away without having a separate ready guard for the service. I figure if we’re exposing a ready promise and then separately a raw object, that is just inviting clients to make the mistake of failing to wait on ready and trying to access the data before it’s in a reliable state. Exposing only a Promise protects me from being able to screw up in this way. This structure also gives us the benefit for free of only having to hit storage once, and we don’t have to have any of that gnarly if (data) { return Promise.resolve(data) } else { return new Promise((resolve, reject) => blablabla } that gives me headaches. Once stuff has come back from the initial read, our exposed Promise is in a resolved state and the service has absolutely nothing else that it needs to do.

Now, we need a way to save new values. Yes, it would be feasible to have stash() take no arguments and simply save the state of an object kept in the service, but then we have lost the elegance of exposing only a Promise and will have to keep a separate raw Preferences object. Having the same data in two places is an incitement to bugs about what happens when they don’t agree, so it’s something I try my best to avoid. Since a function call to the service is going to have to be made anyway, why not just have it take an argument representing the new Preferences?

And that’s how I ended up with this idiom of exposing only a Promise in the service and storing the actual object in pages that are interested in it.

1 Like