Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async & Performance Chapter 4 for..of completion signal to iterator #1251

Open
doubleOrt opened this issue Mar 10, 2018 · 1 comment
Open

Comments

@doubleOrt
Copy link

The section is called "Stopping the generator" and here it is:

In the previous example, it would appear the iterator instance for the *something() generator was basically left in a suspended state forever after the break in the loop was called.

But there's a hidden behavior that takes care of that for you. "Abnormal completion" (i.e., "early termination") of the for..of loop -- generally caused by a break, return, or an uncaught exception -- sends a signal to the generator's iterator for it to terminate.

Note: Technically, the for..of loop also sends this signal to the iterator at the normal completion of the loop. For a generator, that's essentially a moot operation, as the generator's iterator had to complete first so the for..of loop completed. However, custom iterators might desire to receive this additional signal from for..of loop consumers.

While a for..of loop will automatically send this signal, you may wish to send the signal manually to an iterator; you do this by calling return(..).

The third paragraph is what I have problems comprehending, how does the for..of loop send the completion signal to the iterator it is iterating? I would assume by calling return, but this is certainly not true because the return method in the following snippet is never called (return would not have been called even if we used a generator):

const x = {
 [Symbol.iterator]: function() {
   return this;
 },
 next: function() {
   typeof y !== 'undefined' ? y++ : y = 0;
   return {
     value: y,
     done: y > 10,
   };
 },
 return: function() {
   console.log('"return" was called!');
   return {done: true};
 }
};

for (let a of x) {
 // this is insignificant
 console.log(a + 10 * 2 / 3);
}

// If the 'for..of' loop sends a completion signal by calling 'return' after all,
// 'return was called' should have been printed to the console by this point.

So I am assuming that you are referring to the finally block inside of a generator, which is always reached ? But then that is certainly not a moot operation (as stated in the paragraph I quoted).

@getify
Copy link
Owner

getify commented Mar 10, 2018

I think that third paragraph is just incorrect. I believe it was something that changed as the spec was being finalized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants