Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values from an array of promises

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. Result as an array of values [1,2]
  2. Result as individual values in order of promise resolution 1,2

So, basically I want to emulate:

  1. Promise.all([one, two])
  2. Promise.resolve(1), Promise.resolve(2)
like image 830
manidos Avatar asked Jan 13 '17 16:01

manidos


1 Answers

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]
like image 54
martin Avatar answered Sep 29 '22 05:09

martin