Javascript 将Bacon.Bus价值与promise价值相结合

Javascript 将Bacon.Bus价值与promise价值相结合,javascript,promise,frp,bacon.js,Javascript,Promise,Frp,Bacon.js,我在FRP土地上迈出了一小步。我有以下代码: # This will eventually get resolved with some value dfd = Promise.defer() promised = Bacon.fromPromise dfd.promise # Values are occasionally being pushed in here bus = new Bacon.Bus # 1. attempt bus.combine promised, (fromBus

我在FRP土地上迈出了一小步。我有以下代码:

# This will eventually get resolved with some value
dfd = Promise.defer()
promised = Bacon.fromPromise dfd.promise

# Values are occasionally being pushed in here
bus = new Bacon.Bus

# 1. attempt
bus.combine promised, (fromBus, fromPromise) ->
   # This is never invoked

# 2. attempt
Bacon.combineAsArray( bus, promised ).onValues (fromBus, fromPromise) ->
   # This is invoked only once for the latest value from the bus

# 3. attempt
promised.sampledBy(bus).onValue (fromPromise, fromBus) ->
   # No invoke here at all

# These are called asynchronously during application lifespan
bus.push obj1
dfd.resolve value
bus.push obj2
bus.push obj3
我想用promise对象的值更新通过总线交付的每个对象,包括在promise解析之前推送到那里的对象。我可以这样做:

bus.onValue (fromBus) ->
    promise.then (fromPromise) ->
        ...
是的,这是可行的,但我只是不喜欢它,我想看看FRP能否更优雅地解决它。请问您有什么建议吗

更新 我在考虑其他的方法。这里是一些背景,实际上发生了什么

# Simple function that creates some object instance (if it haven't been created yet ) and returns it
getObject = (name) ->
   unless obj = list[name]
     obj = new Obj()
     bus.push obj
对于添加到缓存中的每个对象,我需要将一些属性设置为来自承诺的值。基本上我可以这样做:

obj = new Obj()
dfd.promise.then (resolvedValue) ->
    obj.someProperty = resolvedValue
bus.flatMap(
    Bacon.combineAsArray.bind Bacon, promised
).onValue ([fromPromise, fromBus]) ->
    fromBus.specialProperty = fromPromise
这是没有FRP的完全可行的解决方案,但是正如您所知,每个
调用都必须是异步的。它付出的代价是性能降低。我想克服这一点。如果我理解正确,使用FRP它将调用
。然后只调用一次
,然后提供静态值。问题是怎么做

解决了的 退房。简而言之,它可以如下所示:

obj = new Obj()
dfd.promise.then (resolvedValue) ->
    obj.someProperty = resolvedValue
bus.flatMap(
    Bacon.combineAsArray.bind Bacon, promised
).onValue ([fromPromise, fromBus]) ->
    fromBus.specialProperty = fromPromise

看起来您正在查找
flatMap
(再次):


很高兴看到你进步了!只是一个旁注-承诺是一次性的事情,只能解决一次,因此,
Bacon.fromPromise
创建一个只获取一个值或一个错误的流。你为什么要使用这里的延迟?@本杰明格伦鲍姆推迟只是为了举例,所以你可以看到我在中间的某个地方解决它。我认为使用
fromPromise
将关注promise解决方案,而不是保持价值并为任何消费者提供。对不对?将其转换为
.toProperty
?好吧,这看起来与我没有FRP的解决方案完全相同:)我猜FRP没有那么神奇。我更愿意看到一个解决方案,闭包更少,在一个函数调用中同时包含两个值,正如我在三次失败的尝试中所看到的。好吧,关键是它现在确实返回了一个流——我可能没有足够强调这一点。嗯,我明白了,但这只是糖分。闭包仍然在那里:(嗯,FRP总是“只是糖”:-)然而,为了把闭包糖掉,我现在找到了我认为合适的函数:谢谢@Bergi!这看起来确实有点好,虽然我不太喜欢创建新的流,然后必须使用
onValues
,但我想这只是我必须接受的FRP的一部分:)我用工作解决方案做得很小,并对它进行了一点打磨。