Forwarding `return()` in generators

Axel Rauschmayer axel at
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:

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 =;
            if (item.done) {
                forwardReturn = false;
                return item.value;
            yield item.value;
        forwardReturn = false;
    } catch (e) {
        forwardReturn = false;
    } finally {
        if (forwardReturn) {
> 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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list