Automatic iterator.return() in contexts other than for and yield*

Domenic Denicola d at domenic.me
Wed Jan 14 11:40:05 PST 2015


If I recall this came up previously and Allen said it was a bug. (Everything should use .return().) Hopefully he can confirm.

-----Original Message-----
From: es-discuss [mailto:es-discuss-bounces at mozilla.org] On Behalf Of Jason Orendorff
Sent: Wednesday, January 14, 2015 14:37
To: es-discuss
Subject: Automatic iterator.return() in contexts other than for and yield*

In some cases a `for` loop will implicitly call `iterator.return()`:

    function gen() {
        try { yield 0; }
        finally { console.log("return was called"); }
    }

    for (let x of gen())
        throw "fail";  // logs "return was called"

This is to support iterators that want to clean up after themselves.

Destructuring assignment doesn't call `.return()`:

    let obj = {set x(v) { throw "fail"; }}
    [obj.x] = gen();  // return() is not called

Neither do the Map/Set/WeakMap/WeakSet constructors:

    class MySet extends Set {
        add(v) { throw "fail"; }
    }

    let m = new MySet(gen());  // return() is not called

Anyone remember the rationale for this? It seems like we should have just one iteration protocol, and it should be "what `for` loops do", including `iterator.finish()`. The collection constructors should be as mannerly as `for`, right?

Anyone remember the reasoning? Is it something to consider changing in ES7?

-j
_______________________________________________
es-discuss mailing list
es-discuss at mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


More information about the es-discuss mailing list