Last active
October 6, 2017 00:04
-
-
Save samgiles/4969abaa0fd0a6af3661 to your computer and use it in GitHub Desktop.
Returning a Stream in a Promise is an anti-pattern.
This file contains 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
/** 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