更改所有将Promise返回到可观察状态的功能

时间:2019-11-21 04:59:52

标签: javascript promise rxjs

我有一个API,几乎每个函数都返回一个Promise。我想以反应方式使用此API。对于单个情况,它看起来像这样:

source.pipe(
    mergeMap(action => {
        return defer<[]>(() => API.callThatReturnsAPromise()).pipe(
            map(result => {
                return doFancyStuff(result);
            })
        );
    })
)

假设有很多返回诺言的函数(有些带有args,有些则没有)。

是否存在一种优雅的方法来对那些可观察到的对象做出承诺,而无需手动进行延迟包装并传递可能的参数?

预先感谢

2 个答案:

答案 0 :(得分:3)

使用自

source.pipe(
  mergeMap(action => from(API.callThatReturnsAPromise())),
  map(result => doFancyStuff(result))
)

from将promise作为输入并返回可观察值。

const { of, from, fromEvent } = rxjs;
const { mergeMap, map } = rxjs.operators;

let source$ = fromEvent(document.getElementById('source'), 'click');

let API = {
  callThatReturnsAPromise: () => new Promise((resolve, reject) => {
    console.log('resolving');
    resolve('done');
  })
};

const doFancyStuff = val => `Result of promise was: ${val}`;

source$.pipe(
  mergeMap(_ => from(API.callThatReturnsAPromise())),
  map(result => doFancyStuff(result))
).subscribe(val => { console.log(val); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>
<button id="source">Click</button>

答案 1 :(得分:0)

您的问题几乎有答案。

const toObservable=(promiseFn,mapFn)=>
       defer<[]>(() => promiseFn()).pipe(
            map(result => {
                return mapFn(result);
            })
        );


// usage
   api.get=()=>Promise.resolve('ok')
   mapFn=(value)=>...your map logic
   toObservable(api.get,mapFn).subscribe()