Open loreanvictor opened 4 years ago
Are you aware of the (ancient) for..on proposal?
Edit: sorry, meant https://github.com/jhusain/asyncgenerator
Yeah I was reading through the original link and wondering how it related (though definitely interesting on its own).
Thanks for sharing. Isn't that proposal actually withdrawn in favor of this proposal?
Edit: still good to know of existence of that proposal, I am going through the discussion on it specifically regarding the for ... on
syntax and its caveats now. Specifically this issue seems to apply to what I've suggested here as well, and while my preference would be for the syntax to instantly subscribe since the idea is that you should not care when values are emitted, based on personal experience it seems it is safer to make the subscription asynchronous, as I have for example used a work-around like this a lot:
// do stuff
setImmediate(() => observable.subscribe(...));
As it stands, the only integration with JavaScript syntax for
Observable
s would be through implementation ofSymbol.asyncIterator
(see this and this). This interop would make basic consumption ofObservable
s rather intuitive:However, the
for await
syntax is designed for pulling values from a generator rather than responding to a source emitting values. This for example can cause confusion because we are waiting for theObservable
to complete (which might not happen), or leads to a necessity for buffering the values of theObservable
so that they can be served when they are pulled by the consumer (which has an overhead and can lead to memory issues).Generally, while it is enticing to use
await
to wait for values from sources that push stuff (Promise
s andObservable
s), there is a clear distinction between the two: while aPromise
only ever pushes one value (so it makes sense to await that one value), anObservable
can push many values, which raises the question of consolidating that behavior with a pulling mechanism (e.g. buffering).An alternative might be an additional syntax support for consumption of
Observable
s, for example through a new keyword:Which would be translated to:
Or with a scoped variable set to emitted value:
Which would be roughly equivalent to:
Inspiring Examples
Aborting
Similar to
for
loops, it can supportcontinue
andbreak
keywords:Which would roughly translate to:
Error and Completion Handling
It could also be extended with
catch
andfinally
keywords for error/completion handling:Which would be roughly equivalent to
EDIT: as discussed here, it might be a good idea to make the subscription process asynchronous to make the behavior a bit more predictable.