简体   繁体   English

承诺RxJS5中的可观察对象

[英]Promisify for Observables in RxJS5

Is it possible to create observables similar to how Bluebird's promisify works? 是否可以创建类似于Bluebird的promisify工作方式的可观察promisify

Reference: http://bluebirdjs.com/docs/api/promise.promisify.html 参考: http : //bluebirdjs.com/docs/api/promise.promisify.html

Regular way to handle callbacks 处理回调的常规方法

someFunc = callback => handleCallback(callback)

Handling callbacks with a Promise 用Promise处理回调

someFunc = callback => (
    new Promise(resolve => handleCallback(resolve))
    .then(callback)
)

Fancy Bluebird wrapper around manually handling callbacks with a Promise 精美的Bluebird包装器,用Promise手动处理回调

someFunc = callback => (
    Promise.promisify(handleCallback)()
    .then(callback)
)

In the same vein, a similar requirement is required for observables: 同样,可观测对象也需要类似的要求:

Observable Creation 可观察的创造

someFunc = callback => (
    Rx.Observable
    .create(observer => (
        handleCallback(() => observer.next())
    ))
    .subscribe(callback)
)

Callback Observable Wrapper 回调可观察包装

someFunc = callback => (
    Rx.Observable
    .fromCallback(handleCallback)
    .subscribe(callback)
)

The proper way to handle this is with the bindCallback method. 处理此问题的正确方法是使用bindCallback方法。

The solution to this problem would be: 该问题的解决方案是:

someFunc = callback => (
    Rx.Observable
    .bindCallback(handleCallback)()
    .subscribe(callback)
)

Since bindCallback returns a function, the arguments you'd pass in before the final callback arg are passed into the returned function. 由于bindCallback返回一个函数,因此您在最终回调arg之前传递的参数将传递给返回的函数。

There's also bindNodeCallback which is exactly the same except the first arg returned is a possible error message as you'd normally see in Node.js callbacks. 还有一个bindNodeCallback完全一样,只不过返回的第一个arg是可能的错误消息,正如您通常在Node.js回调中看到的那样。

Since both of these methods only fire once and then automatically get unsubscribed, you may want to use fromEventPattern instead depending on your needs. 由于这两种方法仅触发一次,然后自动取消订阅,因此您可能需要根据需要使用fromEventPattern It will keep firing observer.next() anytime the callback is called. 每当调用该回调函数时,它将继续触发observer.next()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM