Javascript 更改将承诺返回为可观察的所有函数

Javascript 更改将承诺返回为可观察的所有函数,javascript,promise,rxjs,Javascript,Promise,Rxjs,我有一个API,其中几乎每个函数都返回一个承诺。我想以一种反应式的方式使用这个API。对于单个案例,它如下所示: source.pipe( mergeMap(action => { return defer<[]>(() => API.callThatReturnsAPromise()).pipe( map(result => { return doFancyStuff(result);

我有一个API,其中几乎每个函数都返回一个承诺。我想以一种反应式的方式使用这个API。对于单个案例,它如下所示:

source.pipe(
    mergeMap(action => {
        return defer<[]>(() => API.callThatReturnsAPromise()).pipe(
            map(result => {
                return doFancyStuff(result);
            })
        );
    })
)
source.pipe(
合并映射(操作=>{
return defer(()=>API.callthattreturnsapromise()).pipe(
映射(结果=>{
返回doFancyStuff(结果);
})
);
})
)
假设有很多函数返回一个承诺(有些带有args,有些没有)

有没有一种优雅的方式可以让这些承诺成为可观察的,而不必手动用延迟包装和处理可能的论点?


提前谢谢

你的问题几乎有答案了

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()
const toObservable=(promiseFn,mapFn)=>
延迟(()=>promiseFn()).pipe(
映射(结果=>{
返回mapFn(结果);
})
);
//用法
api.get=()=>Promise.resolve('ok'))
mapFn=(值)=>…您的映射逻辑
toObservable(api.get,mapFn.subscribe())
从中使用

source.pipe(
  mergeMap(action => from(API.callThatReturnsAPromise())),
  map(result => doFancyStuff(result))
)
from将承诺作为输入,并返回可观察的

const{of,from,fromEvent}=rxjs;
const{mergeMap,map}=rxjs.operators;
让source$=fromEvent(document.getElementById('source'),'click');
设API={
CallThatReturnsPromise:()=>新承诺((解决,拒绝)=>{
console.log('resolving');
决议(“完成”);
})
};
const doFancyStuff=val=>`承诺的结果是:${val}`;
source$.pipe(
mergeMap(=>from(API.callThatReturnsAPromise()),
映射(结果=>doFancyStuff(结果))
).subscribe(val=>{console.log(val);})


单击
,或者您可以使用fromWith,因为在连接任何处理程序之前,承诺已在执行。我不喜欢这种行为。承诺是在被创造的时候执行的。合并贴图在源发出之前不会激发。请参阅我添加的可运行代码段。在单击使源发出的按钮之前,可以在不创建承诺的情况下设置可观察链。调用API.callThatReturnsAPromise()运行承诺,从(API.callThatReturnsAPromise())运行承诺,否则如何包装承诺而不创建承诺?mergeMap函数在源发出与您的问题完全相同的行为之前不会创建可观察的包装承诺,因此这正是您想要的。感谢您的澄清!