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

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

问题描述

我正在使用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/参考/Global_Objects/Promise/all

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

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