skrat skrat - 1 month ago 15
Javascript Question

Continuous Promise/A+ loading

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.

Answer

What you're talking of is more a Stream than Promises - maybe there's a better fitting library. If not, you might want to have a look at my "Lazy Promise Stream" implementation.

How would this [polling] translate to asynchronous, Promise/A+ enabled code?

The producer()'s next() method would return promises. Then, you'd loop over them in a recursive manner:

function getNext() {
    return p.next().then(function(data) {
         consumer.update(data);
         return getNext();
    });
}
getNext();

The returns could be omitted if you knew it was an infinite stream without errors, as getNext() would be always pending