Preserve order of results when operating asynchronously on a list

萝らか妹 提交于 2020-01-05 08:58:28

问题


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 asynchronously but retain the original ordering?

Here's the fiddle http://jsbin.com/papunixume/edit?html,js,console

// clear console every single run
console.clear()

// create promise
const cp = (msg, timeout) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(msg)
    }, timeout)
  })
}

const a = cp('a', 1000)
const b = cp('b', 500)
const c = cp('c', 800)

Rx.Observable.of([a, b, c]).subscribe(val => {
  val.map(res => {
    res.then(x => console.log(x))
  })
})

Result is

"b"
"c"
"a"

Expected

"a"
"b"
"c"

回答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.



来源:https://stackoverflow.com/questions/42886224/preserve-order-of-results-when-operating-asynchronously-on-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!