我希望对数组的每个元素执行异步操作,并在字典中收集其结果。我目前的做法是:
let asyncOp = () => Rx.Observable.interval(300).take(1);
let dict = {};
Rx.Observable.from(['a', 'b'])
.mergeMap(el => asyncOp()
.map(asyncOpRes => dict[el] = asyncOpRes)
.do(state => console.log('dict state: ', dict))
)
.takeLast(2)
.take(1)
.map(() => dict)
.subscribe(res => console.log('dict result: ', res));
<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>
基本上,这像我想要的那样工作,但它似乎是RxJs操作符的一个笨拙的用法。因此,我需要以下方面的帮助:
我想我缺少了一个RxJS操作符,它帮助我简化了这个过程。
发布于 2016-09-06 23:19:12
要“对数组的每个元素执行异步操作并在字典中收集其结果”,可以使用mergeMap
和reduce
函数对代码进行显著简化:
import * as Rx from "rxjs/Rx";
const asyncOp = () => Rx.Observable.interval(300).take(1);
Rx.Observable.from(["a", "b"])
// Perform the async operation on the values emitted from the
// observable and map the emitted value and async result into
// an object.
.mergeMap((key) => asyncOp().map((result) => ({ key, result })))
// Use reduce to build an object containing the emitted values
// (the keys) and the async results.
.reduce((acc, value) => { acc[value.key] = value.result; return acc; }, {})
.subscribe((value) => { console.log(value); });
https://stackoverflow.com/questions/39353780
复制相似问题