diff --git a/README.md b/README.md index b94ac5d..9ea4787 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,10 @@ read from one pull-stream, then the next, then the next... -when one stream end (unless it errored) call a function -to get the next stream. much like [pull-cat](https://github.com/pull-stream/pull-cat) +when one stream end (unless it errored) call a function to get the next +stream. there is also a function that takes an asynchronous function. + +much like [pull-cat](https://github.com/pull-stream/pull-cat) except creates streams by calling a function instead of takeing them out of an array. in particular, this is useful for making a read stream that reconnects diff --git a/async.js b/async.js new file mode 100644 index 0000000..e6f99dc --- /dev/null +++ b/async.js @@ -0,0 +1,36 @@ +var noop = function () {} + +module.exports = function (next) { + var stream + return function (abort, cb) { + if(!cb) throw new Error('callback required!') + if(abort) { + if(stream) stream(abort, cb) + else cb(abort) + } + else more() + + function more () { + if(stream) send() + else { + next(function (error, nextStream) { + if(error) return cb(error) + if(!nextStream) return cb(true) + stream = nextStream + send() + }) + } + } + + function send () { + stream(null, function (err, data) { + if(err) { + stream = null + if(err === true) setTimeout(more, 100) + else cb(err) + } + else cb(null, data) + }) + } + } +} diff --git a/package.json b/package.json index 6fd3b7e..4be21e3 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,9 @@ "url": "git://github.com/dominictarr/pull-next.git" }, "dependencies": {}, - "devDependencies": {}, + "devDependencies": { + "pull-stream": "^3.4.5" + }, "scripts": { "test": "set -e; for t in test/*.js; do node $t; done" }, diff --git a/test/async.js b/test/async.js new file mode 100644 index 0000000..fc3e880 --- /dev/null +++ b/test/async.js @@ -0,0 +1,23 @@ +var assert = require('assert') +var pull = require('pull-stream') +var asyncNext = require('../async') + +var arrays = [ + ['a', 'b', 'c'], + ['d', 'e', 'f'] +] + +pull( + asyncNext(function (cb) { + if (arrays.length === 0) cb(null, false) + else cb(null, pull.values(arrays.shift())) + }), + pull.collect(function (err, data) { + assert.ifError(err, 'no error') + assert.deepEqual( + data, + ['a', 'b', 'c', 'd', 'e', 'f'], + 'pulls all data' + ) + }) +)