Wait for multiple promises to finish
Solution 1:
You can use
removeAll() {
Promise.all([
this.storage.remove(key1),
this.storage.remove(key2),
this.storage.remove(key3),
]).then(value => doSomething());
See also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Solution 2:
You could use Observable.forkJoin
from rxjs
by providing an array of all the observables/promises
. This needs to be done before performing the operation. It's similar to Angular 1's $q.all
.
rxjs version <= 6
Observable.forkJoin([
this.storage.remove(key1),
this.storage.remove(key2),
this.storage.remove(key3)
])
.subscribe(t=> {
var firstResult = t[0];
var secondResult = t[1];
});
rxjs version > 6
import {forkJoin} from 'rxjs';
forkJoin([
this.storage.remove(key1),
this.storage.remove(key2),
this.storage.remove(key3)
])
.subscribe(t=> {
var firstResult = t[0];
var secondResult = t[1];
});
Solution 3:
On rxjs
version > 6 You can do something like this:
import {forkJoin} from 'rxjs';
and do instead of Observable.forkJoin
this:
forkJoin([
this.service1.get(),
this.service2.get()
]).subscribe(data => {
this.data1= data[0];
this.data2 = data[1];
Solution 4:
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.
forkJoin 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 returned by the .remove method.
Observable.forkJoin([
Observable.fromPromise(this.storage.remove(key1)),
Observable.fromPromise(this.storage.remove(key2)),
Observable.fromPromise(this.storage.remove(key3))
])
.subscribe(data => {
console.log(data[0]);
console.log(data[1]);
console.log(data[2]);
});