Forwarding `return()` in generators

Axel Rauschmayer axel at rauschma.de
Tue Mar 24 21:28:08 UTC 2015


Right, it doesn’t look like one needs to know the returned value when forwarding `return()`.

But: you need to guard against other ways of reaching `finally`. Maybe like this:

```js
function* take(n, iterable) {
    let iterator = iterable[Symbol.iterator]();
    n = +n; // make sure it's a number, so that n>0 does never throw
    let forwardReturn = true;
    try {
        while (n > 0) {
            let item = iterator.next();
            if (item.done) {
                forwardReturn = false;
                return item.value;
            }
            yield item.value;
            n--;
        }
        forwardReturn = false;
    } catch (e) {
        forwardReturn = false;
        iterator.throw(e);
    } finally {
        if (forwardReturn) {
            iterator.return();
        }
    }
}
```
> The above code also has the additional nice property that it call `.return()` on the iterator when `n` values have been taken out of it.

That’s not what all the other constructs in ES6 do: they only call `return()` if iteration stops abruptly.

Also missing from this code: checking whether the iterator actually has the methods `return()` and `throw()` and responding accordingly.

-- 
Dr. Axel Rauschmayer
axel at rauschma.de
rauschma.de



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150324/784006f2/attachment.html>


More information about the es-discuss mailing list