Angular2等待多个承诺完成 [英] Angular2 wait for multiple promises to finish

查看:138
本文介绍了Angular2等待多个承诺完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ionic平台的SQLStorage。 remove函数返回一个promise。在我的代码中,我需要删除多个值。当这些都完成后我需要执行一些代码。

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() {

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

    });

  });

};


推荐答案

您可以使用

removeAll() {
  Promise.all([
    this.storage.remove(key1),
    this.storage.remove(key2),
    this.storage.remove(key3),
  ]).then(value => doSomething());

另见 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

这篇关于Angular2等待多个承诺完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆