Is there any way to combine promises in AngularJS 2?
In Angular 1, for instance, I would use $q.all
to combine multiple requests into a single promise.
Is there an equivalent for Angular 2?
Asked
Active
Viewed 9,603 times
4

georgeawg
- 48,608
- 13
- 72
- 95

user2884505
- 525
- 1
- 6
- 19
-
2$q.all did not chain promises, but combined them to resolve when all of them resolved, or reject when the first one rejected. There is no meaning of the order of promises here. You have Promise.all to do the same job. – Tamas Hegedus Dec 21 '15 at 22:12
-
My mistake; I've updated the title and question! – user2884505 Dec 21 '15 at 22:43
2 Answers
14
The http module works in terms of Observables which is different than promises, but you can do both chaining and parallel calls.
Chaining can be done using flatMap and parallel calls can be handled using forkJoin.
Examples:
//dependent calls (chaining)
this.http.get('./customer.json').map((res: Response) => {
this.customer = res.json();
return this.customer;
})
.flatMap((customer) => this.http.get(customer.contractUrl)).map((res: Response) => res.json())
.subscribe(res => this.contract = res);
//parallel
import {Observable} from 'rxjs/Observable';
Observable.forkJoin(
this.http.get('./friends.json').map((res: Response) => res.json()),
this.http.get('./customer.json').map((res: Response) => res.json())
).subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]});
You can find more details and a demo here:
http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
You can also call toPromise()
on an Observable and convert it to a regular promise as well.

TGH
- 38,769
- 12
- 102
- 135
3
I recommend using Observables for Angular 2+ but in case you still need to use Promises you can use the following:
Promise.all(
[
promise1,
promise2,
promise3
]
);

Jeremy
- 3,620
- 9
- 43
- 75