Skip to content

Instantly share code, notes, and snippets.

@sergi
Created September 7, 2011 14:23
Show Gist options
  • Save sergi/1200696 to your computer and use it in GitHub Desktop.
Save sergi/1200696 to your computer and use it in GitHub Desktop.
Test Async Queue + Streams
S = require("./support/jsftp/support/streamer/core");
function queue() {
var next;
var buffer = Array.prototype.slice.call(arguments)
function stream($, stop) { next = $; stream._update() }
stream._update = function _update() {
buffer.push.apply(buffer, arguments)
if (next && buffer.length) {
if (false !== next(buffer.shift())) _update()
}
}
return stream
}
function enqueue(stream, element) {
stream._update.apply(null, Array.prototype.slice.call(arguments, 1))
}
var pasvReqs = queue();
!function recur() {
// Take first element from `pasvReqs` and process it via `processElement` black box that will call
// `recur` once it's done to process next element from the `pasvReqs` queue.
S.head(pasvReqs)(function(element) {
processElement(element, recur)
})
}()
var processElement = function(el, f) {
var cb = function() {
el.callback();
f();
}
setTimeout(cb, parseInt(Math.random() * 1000));
}
enqueue(pasvReqs, { callback: function() { console.log("1..."); }});
enqueue(pasvReqs, { callback: function() { console.log("2..."); }});
enqueue(pasvReqs, { callback: function() { console.log("3..."); }});
@Gozala
Copy link

Gozala commented Sep 7, 2011

Dude @sergi I realized what the problem is:

You need this after line 12:

else next = null

@Gozala
Copy link

Gozala commented Sep 7, 2011

So reason you need that line is that reader stops reading stream by returning false from next. That's also what head does, but since enqueue calls _update which calls next if next && buffer.length this code misbehaves, each call to enqueue will call next. Setting next to null fixes an issue as if condition will be false until next reader starts reading.

Hope this helps!

@sergi
Copy link
Author

sergi commented Sep 7, 2011 via email

@Gozala
Copy link

Gozala commented Sep 8, 2011

Dude your comment is empty!

@sergi
Copy link
Author

sergi commented Sep 8, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment