Created
January 17, 2012 23:26
-
-
Save CrabDude/1629758 to your computer and use it in GitHub Desktop.
Serializing a stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sometimes we need to handle stream results serially... | |
// The question is, is there a better / more obvious way to do this? | |
var fs = require('fs'), | |
streamer = require('streamer'); | |
function serialize(source) { | |
var queue = []; | |
return function stream(next, stop) { | |
var processing = false, | |
completed = false; | |
source(function sourceNext(x) { | |
if (processing) { | |
queue.push(x); | |
return; | |
} | |
processing = true; | |
next(x, function() { | |
processing = false; | |
if (completed && !queue.length) { | |
stop(); | |
} else { | |
sourceNext(queue.shift()); | |
} | |
}); | |
}, function(err) { | |
if (err) return stop(err); | |
completed = true; | |
}); | |
}; | |
} | |
// a simple async list implementation | |
function asyncList(arr) { | |
return function stream(next, stop) { | |
var l = arr.length; | |
arr.forEach(function(v, k) { | |
setTimeout(function() { | |
next(v); | |
if (k===l-1) stop(); | |
}, 50); | |
}); | |
}; | |
} | |
serialize(asyncList([0,1,2,3]))(function(x, next){ | |
console.log('wait: ',x); | |
setTimeout(function() { | |
console.log('continue: ',x); | |
next(); | |
}, 50); | |
}, function() { | |
console.log('completed!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@CrabDude To be fully honest, back when I started with streamer I did not knew there was anything similar. Later people pointed me out node-lazy and streamjs which I looked at, but quickly rejected mainly because of method based approach instead of functional. At this point I'm no longer sure that function based approach was indeed better as I experiment with prototype based solution myself. Once I'll get more confidence with best possible solution, I'm planning to talking with both @pkrumins and @dionyziz about merging our efforts.