Skip to content

Instantly share code, notes, and snippets.

@samgiles
Last active October 6, 2017 00:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samgiles/4969abaa0fd0a6af3661 to your computer and use it in GitHub Desktop.
Save samgiles/4969abaa0fd0a6af3661 to your computer and use it in GitHub Desktop.
Returning a Stream in a Promise is an anti-pattern.
/** Method 1. Use a PassThrough stream */
var PassThrough = require('stream').PassThrough;
function myAsyncContent() {
var myContentStream = new PassThrough();
var streamPromise = getAsyncInfo().then(function(info) {
return createStreamFromInfo(info);
});
streamPromise.then(function(stream) {
stream.pipe(myContentStream);
}).catch(function(error) {
stream.emit('error', error);
});
return myContentStream;
}
/** Method 2. Use the streamcat library (handles Promises/Buffers/Streams for you) 'npm install streamcat --save' */
var streamcat = require('streamcat');
function myAsyncContent() {
var streamPromise = getAsyncInfo().then(function(info) {
return createStreamFromInfo(info);
});
return streamcat([streamPromise]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment