You are treating it like a convenience store, where you walk in, grab an item off the shelf, and walk out of the story with it. Instead, it’s like a special order, where you call up a pizza place, tell them what kind of pizza you want, and leave instructions as to what to do when it’s done (deliver it, hold it for pickup, &c).
The good news is that you are free to do whatever else you want while the pizza is cooked. Imagine if you had to stay on the phone line until the person told you “OK, your delivery person is at your door”. That’s what you’re asking for in your question: how to do that.
So you don’t want to do that. Use the promise’s then method to describe what you want to do once the data is ready:
this.local.get('key').then((val) => {
console.log('localstorage gave me ' + val);
});
That makes the code quite ugly imho, but I suppose it somewhere makes great and stable code?
Here’s the actual code I’ve written that works just fine. But how can this be better optimized? Can I shorten it down to fewer lines of code? I’m sure someone with more JS experience can see that I write shitty code and can do much better.
As I was trying to get at with the pizza analogy, it’s about minimizing what is colloquially called “sneezy code”, where (like a human sneeze), everything comes to a screeching halt waiting for something to happen. The get method can return immediately, and when you chain a then on the promise it returns, that too does not block execution.
As for your code, it looks to me like a prime example of the Deferred antipattern. The syntax of Bluebird is slightly different, but hopefully the fundamental concept will be clear enough. Another good list of pitfalls that tend to trap people new to the world of promises is at Tao of Code.
How do I keep that val in global variable?
Because I want to use that val in other method, so I need to pull it out of promises, then I can use the data freely bcause I keep it in global variable.
Thankyou