Javascript Angular2 等待多个承诺完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37841721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:47:20  来源:igfitidea点击:

Angular2 wait for multiple promises to finish

javascriptangularpromiseionic2

提问by Bas van Dijk

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.

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

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

    });

  });

};

回答by Günter Z?chbauer

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

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

回答by Pankaj Parkar

You could use Observable.forkJoinfrom rxjsby 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.

你可以使用Observable.forkJoinrxjs提供的所有的数组observables/promises。这需要在执行操作之前完成。它类似于 Angular 1 的$q.all.

rxjs version <= 6

rxjs 版本 <= 6

Observable.forkJoin([
   this.storage.remove(key1), 
   this.storage.remove(key2),
   this.storage.remove(key3)
])
.subscribe(t=> {
    var firstResult = t[0];
    var secondResult = t[1];
});

rxjs version > 6

rxjs 版本 > 6

import {forkJoin} from 'rxjs';

forkJoin([
   this.storage.remove(key1), 
   this.storage.remove(key2),
   this.storage.remove(key3)
])
.subscribe(t=> {
    var firstResult = t[0];
    var secondResult = t[1];
});

回答by Pankaj Parkar

On rxjsversion > 6 You can do something like this:

rxjs版本> 6 你可以做这样的事情:

import {forkJoin} from 'rxjs';

and do instead of Observable.forkJointhis:

而不是Observable.forkJoin这样做:

forkJoin([
  this.service1.get(),
  this.service2.get()
]).subscribe(data => {
  this.data1= data[0];
  this.data2 = data[1];

回答by Daniel Pliscki

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.

我不熟悉 IONIC,但假设 storage.remove 正在返回一个承诺,我建议您使用 observables 中的 forkJoin 运算符。

forkJoin takes an array of observables and awaits the execution of all items.

forkJoin 接受一组 observables 并等待所有项目的执行。

Just notice that I had to create 3 new observables from each promise returned by the .remove method.

请注意,我必须从 .remove 方法返回的每个承诺中创建 3 个新的 observable。

Observable.forkJoin([
   Observable.fromPromise(this.storage.remove(key1)), 
   Observable.fromPromise(this.storage.remove(key2)),
   Observable.fromPromise(this.storage.remove(key3))
])
.subscribe(data => {
    console.log(data[0]);
    console.log(data[1]);
    console.log(data[2]);
});

回答by Sandro Almeida

use Promise.all for Promisses and Observable.forkJoin for Observables

对 Promisses 使用 Promise.all,对 Observables 使用 Observable.forkJoin

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:

因为问题是关于 angular(2+) 并且您可能应该使用 Observable 而不是 promises。我将添加一个对我有用的 GET 示例:

import {Observable} from 'rxjs/Rx';

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

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

注意使用 .map() 来处理响应而不是 .subscribe()

回答by JB Nizet

Use Promise.all():

使用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.

Syntax

Promise.all(iterable);

Parameters

iterable

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

Promise.all(iterable) 方法返回一个承诺,该承诺在 iterable 参数中的所有承诺都已解决时解决,或者以第一个通过的承诺拒绝的原因拒绝。

句法

Promise.all(iterable);

参数

可迭代的

一个可迭代的对象,例如一个数组。参见可迭代。