Skip to content

Comment on Node.js stream handbook

Comments

Not hoping to start any sort of flame war, but could someone try to explain this difference between streams and promises? The conceptual difference doesn't seem completely clear to me.

Promises hep deal with asynchronous functions by providing a convenient way to pass success/fail methods in a way some people prefer more than classic callbacks.

Streams are a totally different use case. Streams are used when you want to process data one part at a time without having to have all of the data in memory at once.

*edit: typo

Promises are actually about trust, not syntax. With a callback you have to trust that the function that will invoke your callback (which might not be something you wrote) will only ever call it once, that it will pass through errors, that it won't call both your success and failure callbacks, etc.

With a promise (or rather, following the promise specification) you instead get back an object that you choose how to handle. That object is either pending or else an immutable success or failure result. Either success or failure will be called (not both), and whichever result is called can only be called once. As such, promises allow you to avoid inversion of control and to safely interact with potentially untrusted code.

This great series of articles helped me understand this: http://blog.getify.com/promises-part-2/

You may be interested in going through "A General Theory of Reactivity"[0] from Kris Kowal, creator of the q promise library. It discusses relationships between streams, promises, iterators and generators (although the streams that he discusses are not how Node.js streams are implemented)

[0]: https://github.com/kriskowal/gtor

Cool, I'll have to take some time to read through more of that, but a quick skim actually made clear to me some of the differences I was missing, especially when combined with the other comments.

Basically a promise represents a single (future) value whereas a stream represents zero or more (ordered, future) values.

A queue of promises would be similar to a stream.

With streams you don't wait for them to end. They may never end, in fact.

Which is unlike Promises, which guarantee a single "end," but also don't care when that ends (could have already happened, could happen eventually). Seems similar in nature to a socket connection.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.