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

Isiah Meadows isiahmeadows at
Tue Aug 22 16:30:55 UTC 2017


On Tue, Aug 22, 2017 at 3:36 AM, Marius Gundersen <gundersen at> wrote:
> One of the reasons I think for-of should handle this is because of the error
> handling. [Closing an
> iterator](
> is not trivial, and so having to write that code yourself is error prone.

Very true. Here's how I feel it could be addressed: you could create a
utility function to close an iterator after it throws, like this:

function use(gen, func) {
    const iter = gen[Symbol.iterator]()
    let caught, error, result
    try {
        return result = func(iter)
    } catch (e) {
        caught = true
        error = e
    } finally {
        try {
        } finally {
            if (caught) throw error
            if (result == null || typeof result !== "object" && typeof
result !== "function") {
                throw new TypeError("result must be an object")

Ideally, though, we should have some sort of resource management
system like what I proposed a while back [1], but that's pretty
non-trivial for starters. There's also the issue of I/O being almost
always async in idiomatic JS APIs.


> I originally considered `continue x;` (and `break x;`), but this is already
> used for labels, but it seems `continue with x;` (and `break with x;`) will
> work, as the following throws a syntax error today: `with:
> while(true){continue with;}`. Only problem as you said Isaiah is that you
> can't send an initial value, but at least until
> [`function.sent`](
> proposal is accepted that is not a problem, as there is no way for the
> generator to receive the initial `next` value, so it's not really of much
> value today.

Except it kind of is. The iterator protocol *does* include optional
`throw` and `return` methods [2], and `IteratorClose(iterator,
completion)` uses `return` internally [3].


> And since the `Iterarot.return()` method takes an optional
> value as well, it makes sense to have support for `break with x;`


Isiah Meadows
me at

Looking for web consulting? Or a new website?
Send me an email and we can get started.

More information about the es-discuss mailing list