[英]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
someFunc = callback => handleCallback(callback)
someFunc = callback => (
new Promise(resolve => handleCallback(resolve))
.then(callback)
)
someFunc = callback => (
Promise.promisify(handleCallback)()
.then(callback)
)
In the same vein, a similar requirement is required for observables: 同样,可观测对象也需要类似的要求:
someFunc = callback => (
Rx.Observable
.create(observer => (
handleCallback(() => observer.next())
))
.subscribe(callback)
)
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.