osi osi - 1 year ago 152
Javascript Question

Angular2 wait for multiple promises to finish

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);

});

});

};

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download