question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Streams and promises

See original GitHub issue

I’ve a question on best practices when working with Promises and streams, with specific regards in how to “promisify” them. The example problem I’m trying to solve is with an API that returns a file stream. I then want to use Promise.map with concurrency on a large list of files, so that only c files are streaming at any given time. I’ve solved this to my needs below:

Promise.map(files, function(file){ 
  return new Promise(function(resolve, reject) {
    var stream = API.getStream(file); 
    // Pipe/use stream
    stream.pipe(endPoint);
    stream.on('end', resolve);
    stream.on('error', reject);    
  });
}, {concurrency: 3});

Main question is, is there a more semantic way to accomplish this? I’ve never before had to write new Promise(…) myself, so I have an instinctual feeling I’m missing something. On the other hand, I’m pretty sure it doesn’t make sense to automatically promisify API.getStream.

  • The stream is returned synchronously already
  • You don’t want a promise of a stream, you want a promise of a “finished” stream.
  • You want the underlying stream for piping and other stream specific functions
  • There’s no guarantee that an input is a stream, and not just a general EventEmitter style object.

An example where the API returns a promise of a finished stream.

Promise.map(files, function(file){
  var streamPromise = API.getFinishedStreamAsync(file);
  streamPromise.pipe(streamPromise.stream); // Stream is attached synchronously
  // API now handles stream/promise resolution
  return streamPromise;
}, {concurrency: 3});

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

38reactions
petkaantonovcommented, Oct 8, 2014

It is generic code that can be tucked away in a utility function so it doesn’t clutter application code and obstruct actual application logic.

In your example simplest utility function would be like

function streamToPromise(stream) {
    return new Promise(function(resolve, reject) {
        stream.on("end", resolve);
        stream.on("error", reject);
    });
}

And then the application code is simply

Promise.map(files, function(file) {
    var stream = API.getStream(file);
    stream.pipe(endPoint);
    return streamToPromise(stream);
});
4reactions
beckcommented, Jul 1, 2016

A small addition to @petkaantonov’s solution, suggest adding stream.resume();, otherwise there is no guarantee that the stream will drain and emit end.

Example:

const gs = require('glob-stream');
const through = require('through2').obj;

function streamToPromise(stream) {
  return new Promise(function(resolve, reject) {
    stream.on('end', resolve);
    stream.on('error', reject);
  });
}

function log(data, enc, cb) {
  console.log(data.path);
  cb();
}

const stream = gs.create('./*.txt')
  .pipe(through(log));

streamToPromise(stream)
  .then(() => { console.log('I never print, womp womp'); });

but the print will happen if one uses:

function streamToPromise(stream) {
  return new Promise(function(resolve, reject) {
    stream.on('end', resolve);
    stream.on('error', reject);
    stream.resume();
  });
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Using promises with streams in node.js - Stack Overflow
In this line stream.on("end", resolve(stream.dests[0].path));. you are executing resolve immediately, and the result of calling resolve ...
Read more >
Promise, Observable vs Stream - Level Up Coding
Both Promises and Observables help us to work with the asynchronous functionalities in JavaScript. Promises are values that will resolve in asynchronous ways ......
Read more >
Wrap your streams with promises for fun and profit
Streams are everywhere in node, and once you get the hang of using them, they are delightful. There are many solid articles that...
Read more >
Stream | Node.js v19.3.0 Documentation
The stream/promises API provides an alternative set of asynchronous utility functions for streams that return Promise objects rather than using callbacks. The ...
Read more >
Overview of Promise-Based APIs in Node.js - Future Studio
The stream/promises module provides two promise-supporting methods: - finished : waits for a stream to finish reading, writing or an error ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found