So I'd like to have these continuous, asynchronous, data loading in browser. I like Promises, they're good, aren't they? Fun to program, easy to read.
In my problem, I won't to continuously update some resource in the browser, for example an image. There are two parts then: producer and consumer. In synchronous code it could look like this:
var p = producer(),
data = null;
while (data = p.next()) {
consumer.update(data)
}
How would this translate to asynchronous, Promise/A+ enabled code?
UPDATE
I ended up using the following base class:
class Stream
input : null
output : null
# @param {function} callback
end : (callback) -> @end_callback = callback
# @param {Stream} writable
# @return {Stream}
pipe : (writable) -> writable.input = @ ; @output = writable
# @param {function} callback
# @return {Stream}
data : (callback) ->
setTimeout =>
last = @
chain = [@]
while last.input != null
last = last.input
chain.push(last)
last = chain.pop()
next = =>
thenable = last.read()
if thenable is null and @end_callback
return @end_callback()
thenable.then (value) =>
if not chain.length
callback(value)
@data(callback)
else
last = chain.pop()
last.write(value)
next()
next()
, 0
@
Just implement read
method, returning a Promise
or null, or both read
and write
to create transforming stream.