Source:  Twitter logo

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?


removeAll() {;;;    

Nesting all is a bad practise so I am looking for a decent solution :)

removeAll() {
  return => { => {;        

You can use

removeAll() {
  ]).then(value => doSomething());

See also

84 users liked answer #0dislike answer #084
Günter Zöchbauer profile pic
Günter Zöchbauer

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

.subscribe(t=> {
    var firstResult = t[0];
    var secondResult = t[1];

rxjs version > 6

import {forkJoin} from 'rxjs';

.subscribe(t=> {
    var firstResult = t[0];
    var secondResult = t[1];
35 users liked answer #1dislike answer #135
Pankaj Parkar profile pic
Pankaj Parkar

On rxjs version > 6 You can do something like this:

import {forkJoin} from 'rxjs';

and do instead of Observable.forkJoin this:

]).subscribe(data => {
  this.data1= data[0];
  this.data2 = data[1];
5 users liked answer #2dislike answer #25

Use Promise.all():

The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects.





An iterable object, such as an Array. See iterable.

3 users liked answer #3dislike answer #33
JB Nizet profile pic
JB Nizet

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:

import {Observable} from 'rxjs/Rx';

      this._dataService.getOne().map(one => =one),
      this._dataService.getTwo().map(two => this.two two),
      this._dataService.getN().map(n => this.n = n),
    ).subscribe(res => this.doSomethingElse(, this.two, this.n)); 

note the use one .map() to handle the response rather than .subscribe()

3 users liked answer #4dislike answer #43
Sandro Almeida profile pic
Sandro Almeida

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.

.subscribe(data => {
3 users liked answer #5dislike answer #53
Daniel Pliscki profile pic
Daniel Pliscki

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).