In Angular 1.x I would sometimes need to make multiple http
requests and do something with all the responses. I would throw all the promises in an array and call Promise.all(promises).then(function (results) {...})
.
Angular 2 best practices seem to point towards the use of RxJS's Observable
as a replacement to promises in http
requests. If I have two or more different Observables created from http requests, is there an equivalent to Promise.all()
?
Conversion to Promiseslink. The similarity between Observables and Promises is that both collections may produce values over time, but the difference is that Observables may produce none or more than one value, while Promises produce only one value when resolved successfully.
The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.
forkJoin - When all observables complete, emit the last emitted value from each. combineLatest - When any observable emits a value, emit the latest value from each.
The more straightforward alternative for emulating Promise.all is to use the forkJoin operator (it starts all observables in parallel and join their last elements): A bit out of scope, but in case it helps, on the subject of chaining promises, you can use a simple flatMap : Cf. RxJS Promise Composition (passing data)
RxJS Observables. An Observable is a unique Object similar to a Promise that can help manage async code. Observables are not part of the JavaScript language yet but are being proposed to be added to the language. Since we can’t use a built-in Observable, we rely on a popular Observable library called RxJS.
One of the significant differences between Observables and Promises is Observables support the ability to emit multiple asynchronous values. A Promise once it has resolved its async value it completes and can no longer be used. The one shot use falls short for the use case where we need multiple values over time.
Most people will first encounter RxJS through observables. An observable will typically look something like this: These are based around the observable model or contract. Next is what handles emitting events in the stream. Complete frees up the observables resources and essentially ends the stream.
The more straightforward alternative for emulating Promise.all
is to use the forkJoin
operator (it starts all observables in parallel and join their last elements):
A bit out of scope, but in case it helps, on the subject of chaining promises, you can use a simple flatMap
: Cf. RxJS Promise Composition (passing data)
Update May 2019 using RxJs v6
Found the other answers useful, and wished to offer an example for the answer offered by Arnaud about zip
usage.
Here is a snippet showing the equivalence between Promise.all
and the rxjs zip
(note also, in rxjs6 how zip now gets imported using "rxjs" & not as an operator).
import { zip } from "rxjs";
const the_weather = new Promise(resolve => {
setTimeout(() => {
resolve({ temp: 29, conditions: "Sunny with Clouds" });
}, 2000);
});
const the_tweets = new Promise(resolve => {
setTimeout(() => {
resolve(["I like cake", "BBQ is good too!"]);
}, 500);
});
// Using RxJs
let source$ = zip(the_weather, the_tweets);
source$.subscribe(([weatherInfo, tweetInfo]) =>
console.log(weatherInfo, tweetInfo)
);
// Using ES6 Promises
Promise.all([the_weather, the_tweets]).then(responses => {
const [weatherInfo, tweetInfo] = responses;
console.log(weatherInfo, tweetInfo);
});
The output from both are the same. Running the above gives:
{ temp: 29, conditions: 'Sunny with Clouds' } [ 'I like cake', 'BBQ is good too!' ]
{ temp: 29, conditions: 'Sunny with Clouds' } [ 'I like cake', 'BBQ is good too!' ]
forkJoin works fine too, but I'd prefer combineLatest since you don't need to worry about it taking the last value of observables. This way, you can just get updated whenever any of them emit a new value too (e.g. you fetch on an interval or something).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With