Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Break work in for-of loop when stopping a Generator?

So there are some ways to stopping a Generator in for of loop, but how does break send a signal to the Generator(in comparison with return in for-of)?

please consider the code.

As an example, the preceding code just increases a value from 1 to 10 ,and do pause and resume in between.

function *Generator() {

    try {
        var nextValue;

        while (true) {
            if (nextValue === undefined) {
                nextValue = 1;
            }
            else {
                nextValue++;
            }

            yield nextValue;
        }
    }
    // cleanup clause
    finally {
        console.log( "finally has been reached." );
    }
}

it loops over it 10 times by using for of:

var it = Generator();// it gets Generator's iterator

for (var v of it) {
    console.log(v); 

    if (v > 9) {

           //it.return("stop");//this is another tool for stopping, but it doesn't stop immediately.

           break; 

           console.log("it won't run");//this line won't run
    }
} 

When it.return() is used by the way, the implementation's clear(it is the main Object and has got the control, but what about the break?);

like image 818
Mehdi Raash Avatar asked Feb 21 '17 23:02

Mehdi Raash


1 Answers

Iterable objects like your it generator object have a property with the key Symbol.iterator that is a function returning an iterator. Iterators are required to have a .next() method to advance from one item to the next. Then can also optionally have a .return() method, which is called when you break, return, or throw, causing the for..of to stop before it runs to completion. So in your case, break; will automatically call it.return().

The other side of it is that on ES6 generator, .next() makes it resume execution at the currently paused yield, and .return() makes it act like the yield is a return statement, so break inside the loop causes yield nextValue; to behave like return;, which will exit the generator and trigger the finally block.

like image 51
loganfsmyth Avatar answered Nov 14 '22 05:11

loganfsmyth