我正在用BaconJS在玻璃钢土地上迈出一小步。我有以下代码:
# 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我希望通过总线更新每个交付的对象,其中包括那些在承诺被解析之前被推到那里的对象的值。我可以这样做:
bus.onValue (fromBus) ->
promise.then (fromPromise) ->
...是的,那有效,但我只是不喜欢它,我想看看玻璃钢是否能更优雅地解决它。请问您有什么提示吗?如何使用纯玻璃钢?
更新
我在考虑其他的方法。下面是一些实际发生的背景..。
# 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如果没有玻璃钢,这是完全可行的解决方案,但是您可能知道,每个.then调用都是异步的。它用性能下降来支付它的代价。我想克服这一点。如果我正确理解它,使用玻璃钢,它只会调用一次.then,然后提供静态值。问题仍然是怎么做..。
解出
看看小提琴。简而言之,它可以是这样的:
bus.flatMap(
Bacon.combineAsArray.bind Bacon, promised
).onValue ([fromPromise, fromBus]) ->
fromBus.specialProperty = fromPromise发布于 2014-05-14 23:40:38
看起来您正在寻找flatMap (再次):
busValuesWithPromise = bus.flatMap (busValue) ->
Bacon.combineAsArray(promised, busValue)
busValuesWithPromise.onValues (fromPromise, fromBus) ->
# every bus update, together with the promise valuehttps://stackoverflow.com/questions/23665879
复制相似问题