javascript - 等待多个 promise 完成

标签 javascript angular promise ionic2

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

我怎样才能等待所有这些然后执行回调函数?

代码:

removeAll() {    
  this.storage.remove(key1);
  this.storage.remove(key2);
  this.storage.remove(key3);    
}

全部嵌套是一种不好的做法,所以我正在寻找一个合适的解决方案:)

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

关于javascript - 等待多个 promise 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37841721/

相关文章:

php - 从 Superfish 菜单 Drupal 7 中删除标题

javascript - UI-router 空参数导致导航到错误的路线

javascript - 带有 Typeform 的 Nuxt.js 导致我强制重新加载页面

JavaScript 编码无法正常工作

javascript - 如何将类型添加到 for with typescript 中定义的变量?

javascript - 如果我在异步调用中省略 "await",操作是否仍会完成?

javascript - read.ts(6133)模块 '"../../../node_modules/rxjs/observable/combineLatest "' has no exported member 'combineLatest'.ts(2305)

Angular2 @angular/cli e2e 错误 : tunneling socket could not be established, statusCode=400

javascript - 如何用Q嵌套序列?

angular - 您将如何修复此 "Promise<any>' 提供与签名 '(value: any): {} | PromiseLike<{}>"不匹配的错误