Proposal: for-of-withas a way to provide a value to the generator

James Browning thejamesernator at gmail.com
Mon Aug 28 03:07:11 UTC 2017


I've always wanted a way to do something similar so that operators over
coroutines are virtually the same as over iterables, although I don't know
we need it to be part of a `for-of` loop, simply having a set of utilities
that help with dealing with coroutines would be nice.

In particular just a set of utilities that expose the internal operators in
particular `GetIterator`, `IteratorNext` and `IteratorClose` would be
particularly nice as there's subtleties that aren't entirely obvious from
the outside especially once async iterators are part of the spec.

For example this might look sound:

```js
function getIterator(iterable) {
    if (typeof iterable[Symbol.iterator] === 'function') {
        return iterable[Symbol.iterator]()
    } else {
        throw new TypeError(`object is not iterable`)
    }
}
```

But in the spec it actually stores a reference to the original method
(presumably in case the method self-deletes in a getter or something weird
like that) so it's actually:

```js
function getIterator(iterable) {
    const method = iterable[Symbol.iterator]
    if (typeof method === 'function') {
        return Reflect.apply(method, iterable, [])
    } else {
        throw new TypeError(`object is not iterable`)
}
```

Which while a rare difference may lead to some strange bugs, this feature
is shared amongst all of those methods, other subtleties include `for-of`
loops not passing *any* arguments to `iterable.next` and that objects must
be checked for as `IteratorNext` results.

Async iterators will be even worse for these sort've bugs as anyone
implementing things that use async iterators directly will need to be aware
of `AsyncFromSyncIterator` in addition to everything from sync iterators.

Because these can be done in userland (assuming we ignore that
`AsyncFromSyncIterator` will have to a custom class as the real
AsyncFromSyncIterator is mostly just a spec device), I think I'll try to
implement them as a library and see how that works out with a few utility
functions like `using` which will auto close iterators after completion.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170828/dbb954a9/attachment-0001.html>


More information about the es-discuss mailing list