Thursday 19 October 2017

Returning a stream from an async function

I'm writing a function right now that returns a stream. But I just realized I need to do some async work before I return the stream (I need to connect to Consul to find the address of the server I'm going to fetch some data from).So this used to be:import pump from 'pump'; import JSONStream from 'JSONStream'; getResponses() { const answer = new JSONStream.parse('*'); pump(request({uri: 'http://server/responses'}), answer); return answer } and this was nice and simple, but now I'm going to do an async call which means this function now has to take a callback or return a Promise which resolves to the stream. This seems kind of weird to me, because streams and Promises are two different async constructs, and it feels wrong to be mixing them. So I could do:getResponses() { const answer = new Transform({ objectMode: true, transform(chunk, encoding, callback) {callback(null, chunk);} }); distributed.findService('api') .then( apiService => { pump( request({uri: `http://ift.tt/2gsL3sA`}), new JSONStream.parse('*'), answer ); }, err => { answer.destroy(err); } ); return answer; } Now from the caller's side, it's just a stream again. But am I overthinking this? :P

Submitted October 19, 2017 at 03:36PM by jwalton78

No comments:

Post a Comment