Open lukeed opened 7 months ago
Why async iterator in the first place? Why not EventTarget
, like built-in EventSource
?
EventTargets aren't composable (like AsyncIterators or ReadableStreams) and so force you to use event-based callback handling, which is fine, but that makes the code/data control flow less obvious. Plus so much of the EventTarget
API isn't strictly necessary for parsing or surfacing SSE messages. Most of the code (either mine or polyfill'd) would be to support the EventTarget itself, not the utility.
ReadableStreams aren't treated as AsyncIterators everywhere yet; see support. As of now, only Deno >= 1.0, Node >= 16.5.0, and Firefox >= 110 support this feature.
Until this is true, I don't think it makes sense to make this change. It seems pretty straightforward to convert this into a ReadableStream
, so why not provide a helper function to handle the conversion for this instead?
What about the opposite case, how simple is it to convert a ReadableStream
into an AsyncIterator
where the protocol is not implemented yet?
I manually iterate the async iterator now until completion as of now. Works well & bypasses all the compat issues.
In addresses that #3 issue, I had a ReadableStream branch going and it was a bit more code to set up. Not necessarily a deal breaker, however I do think not being able to for await (let x of events) {...}
in common envs is more of a deal breaker
Perhaps
events()
should be aReadableStream
ofServerSentMessage
s instead of an AsyncIterator.Practically, the stream could still be used with this syntax:
The difference would be that a ReadableStream (I think, although am fairly confident) performs better and you have the ability to easily pipe it to some Writer or Transformer stream. For example, imagine:
To do the same now, with the AsyncIterator, you have to manually loop the iterable and apply your work; or, convert it to a
ReadableStream
to be able to do any pipe-work (mentioned above):Considerations
ReadableStream
s aren't treated as AsyncIterators everywhere yet; see support. As of now, only Deno >= 1.0, Node >= 16.5.0, and Firefox >= 110 support this feature.AsyncGenerator
s (whatevents()
currently returns) is supported in significantly more places. This may be reason alone to keep what's here.The
ReadableStream.from
shortcut is available in Deno >= 1.35, Node >= 20.6.0, and Firefix >= 20.6. However, there's an easy manual workaround when this static method isn't available (see above)