I am using the SQLStorage from the Ionic platform. The remove function returns a promise. In my code I need to remove multiple values. When these are all finished I need to execute some code.
How can I wait for all of these and then execute a callback function?
Code:
removeAll() {
this.storage.remove(key1);
this.storage.remove(key2);
this.storage.remove(key3);
}
Nesting all is a bad practise so I am looking for a decent solution :)
removeAll() {
return this.storage.remove(key1).then(() => {
this.storage.remove(key2).then(() => {
this.storage.remove(key3);
});
});
};
On
rxjs
version > 6 You can do something like this:and do instead of
Observable.forkJoin
this:You can use
See also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Use Promise.all():
You could use
Observable.forkJoin
fromrxjs
by providing an array of all theobservables/promises
. This needs to be done before performing the operation. It's similar to Angular 1's$q.all
.use Promise.all for Promisses and Observable.forkJoin for Observables
as the question is about angular(2+) and you problably should have been using Observable instead of promises. i`ll add a GET example that worked for me:
note the use one .map() to handle the response rather than .subscribe()
I'm not familiar with IONIC, but assuming that storage.remove is returning a promise I would suggest you to use forkJoin operator from observables.
ForJoin takes an array of observables and awaits the execution of all items.
Just notice that I had to create 3 new observables from each promise return by the .remove method.