How to get the LocalStorage value out of promise scope

The thing to keep in mind with promises is that they represent asynchronous tasks. So you can manipulate the data outside of the scope promise, but it has to be after the promise has finished.

So in your exact example, you can’t print the value outside of the scope, for a multitude of reasons. First being the fact that output isn’t in the scope that you’re trying to print it. Secondly, there’s no guarantee that the promise has finished executing before you’re trying to print the data it returns.

One way you can get around this, is save a reference to the promise and operate off of that, i.e.

var dataPromise = this.local.get("name");

...elsewhere...
dataPromise.then(data => {
   console.log(data);
});

Does this all make sense? I’m not sure what your experience with Javascript is, and so I hope I haven’t overloaded you. I know it took me a bit to wrap my head around promises the first time I ran into them :slight_smile:

2 Likes