Forwarding `return()` in generators

Axel Rauschmayer axel at rauschma.de
Tue Mar 24 18:44:00 UTC 2015


AFAICT, `return()` throwing an exception (versus performing a `return`) is necessary if you want to forward it like in the following code:

```js
function* take(n, iterable) {
    let iterator = iterable[Symbol.iterator]();
    try {
        while (n > 0) {
            let item = iterator.next();
            if (item.done) {
                return item.value;
            }
            yield item.value;
            n--;
        }
    } catch (e) {
        if (e instanceof ReturnException) {
            iterator.return(e.returnValue); // forward
        }
        ···
    }
}
```

Seems important w.r.t. composability of generators.

Axel

-- 
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/c6100797/attachment.html>


More information about the es-discuss mailing list