Gulp: How to create a stream from a promise of an array of streams?

时间:2015-11-11 15:58:57

标签: node.js gulp event-stream

I have a list of tasks that are initiated by an async function. I end up with a promise of an array of streams. I need to merge these streams into a single stream and return that to Gulp. The following is what I came up with. It's kind of clunky. Is there a better way to do this?

return es.readable(function(count, callback) {
    var dest = this;
    promise.then(function(streams) {
        es.merge.apply(null, streams)
            .on('end', dest.emit.bind(dest, 'end'))
            .on('data', dest.emit.bind(dest, 'data'))
            .on('error', dest.emit.bind(dest, 'error'));
    });
});

1 个答案:

答案 0 :(得分:0)

es.merge返回可读流。
没有理由再用es.readable创建一个 我有很长一段时间没有node.js经验,但想想我写的任何有用的东西:)

// async way
function merged(promise, next) {
    promise.then(function(streams) {
        next(null, es.merge.apply(null, streams));
    }, next);
}
// like a promise
function merged(promise) {
  return {
    then: function(ok, fail) {
      promise.then(function(streams) {
        ok(es.merge.apply(null, streams));
      }, fail);
    }
  }; 
}

用法:

merged(promise, function(err, stream){stream.pipe(anyWritable);}); // async
merged(promise).then(function(stream){stream.pipe(anyWritable);}); // then