This is an example of the explicit Promise construction antipattern. If you see a blog tutorial recommend this, it’s almost guaranteed that they don’t understand how to use Promises.
I still struggle with the initial issue though, as I don’t know how to properly init my Ionic storage and handle the promises. Could someone maybe provide me an example link/application/book which I could use for data initializing and promises? Just the basic approach for “if Ionic Storage exists, return it, if not, create a new one with local data and return it”
This is exactly the thing, when my initialGet does not exist, I do not want to return an already stored value, I want to execute another promise (a promise to first set the data, and then return it).
This means:
const valueIfNothingInStorage: string = 'foo';
initialize(key: string): Promise<string> {
return this.storage.get(key)
.then((initialGet: string) => {
if (initialGet) {
return initialGet }
else {
//set the storage with init data and return it
this.storage.set(key, 'someData');
return this.storaget.get(key);
}
}
}
I think the above does not work like that for two reasons:
the this.storage.set is an actual promise
the return this.storage.get(key) returns a promise while it should return a value.
async/await is Promises for people who don’t like to type their variables. Slightly cynical of me, but I think that’s a pretty good assessment. At least it was in my case. I tried async/await and went back to Promises because I found myself getting into bad habits. If you want a different opinion, you could look at @Judgewest2000’s code repos. He uses async/await successfully.
Thanks once more! But small question: Isn’t that a promise within a promise, and as such undesired as promised should be concatenated via .then and not inside their function?
So i’m not nesting asynchronous functions. promise1.then(_ => promise2.then(something synchronous))
is fine. From an async perspective, it’s the same as promise1.then(_ => promise2)
which of course is ok.
I don’t understand your question. The then method is not a Promise. The then method returns a Promise. It isn’t wrong to put a Promise inside a then method.
I think you ought to spend some time reading the Promise API.