I've just started learning this amazing stuff. I can't figure out how to get values from an array of promises. Here's where am at:
const one = new Promise(resolve => {
setTimeout(() => {
resolve(1);
}, 1000);
})
const two = new Promise(resolve => {
setTimeout(() => {
resolve(2);
}, 2000);
})
const observable = Rx.Observable.from([one, two]);
observable.subscribe(v => console.log(v));
I get in console:
Promise { <pending> }
Promise { <pending> }
I'd like to get:
[1,2]
1,2
So, basically I want to emulate:
Promise.all([one, two])
Promise.resolve(1), Promise.resolve(2)
Static method Observable.from()
emits each item in the array so what you have right now will just emit two Promise
objects:
You're dealing with so called Higher-order Observables (aka Observables emitting Observables). This is in RxJS 5 easily solvable with concatAll
or mergeAll
depending on whether you care about the order they are specified or they can be collected as the resolve.
RxJS 5 treats Observables, Promises, iterators, array (and array like objects) the same way. This means we use your Promises just like they were Observables.
I'm using mergeAll
here to show that the second Promise finished first even though they're defined in the opposite order [one, two]
.
const one = new Promise(resolve => {
setTimeout(() => {
resolve(1);
}, 1000);
})
const two = new Promise(resolve => {
setTimeout(() => {
resolve(2);
}, 500);
})
// Result as individual values in order of promise resolution 2,1
Rx.Observable.from([one, two])
.mergeAll()
.subscribe(v => console.log('mergeAll: ' + v));
// Result as an array of values [2,1]
Rx.Observable.from([one, two])
.concatAll()
.toArray()
.subscribe(v => console.log(v));
See live demo: https://jsbin.com/tigidon/4/edit?js,console
This prints to console:
mergeAll: 2
mergeAll: 1
[2, 1]
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