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); }); }); };
Approach 1: In this approach, we will use Promise. all() method which takes all promises in a single array as its input. As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together.
You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function. Copied!
The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result.
The order functions resolve or reject in don't matter here since the . map(p => p. catch(e => e)) part turns all rejections into resolved values, so Promise. all still waits for everything to finish whether individual functions resolve or reject, regardless of how long they take.
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
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
.
Observable.forkJoin([ this.storage.remove(key1), this.storage.remove(key2), this.storage.remove(key3) ]) .subscribe(t=> { var firstResult = t[0]; var secondResult = t[1]; });
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]; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With