Skip to content Skip to sidebar Skip to footer

Preserve Order Of Results When Operating Asynchronously On A List

I have an asynchronous function that processes requests from a list, but when each request is done, it's not ordered like before declared (since it's async). How can I fetch asynch

Solution 1:

This really depends on what and how you need to work with the Promises. What you have now doesn't need RxJS at all because you're just creating an array of Promises and then calling then() on each of them.

If you want to do in more "RxJS way" you can collect results from the Promises as they arrive while maintaining the same order with the concatMap() operator:

Rx.Observable.from([a, b, c])
  .concatMap(promise => promise)
  .subscribe(val => console.log(val));

The magic happens inside concatMap() because it recognizes an instance of a Promise class and handles them in a special way (chains them with then() and reemits theirs result).

See demo: http://jsbin.com/gobayoy/4/edit?js,console

Or you can wait until all of the Promises complete and then emit all their results as a single array with forkJoin():

Rx.Observable.forkJoin(a, b, c)
  .subscribe(val =>console.log(val));

See demo: http://jsbin.com/zojuya/2/edit?js,console

Again, RxJS handles Promises automatically so forkJoin() is able to wait for all Promises to finish without you worrying about it.

Post a Comment for "Preserve Order Of Results When Operating Asynchronously On A List"