last value from iterator

# Mark Volkmann (10 years ago)

I thought that when an iterator returns done: true, the value should not be used. However, if a generator function ends by returning a value, done will be true when that value is returned and the value should be used. Given this, how can a consumer know the correct way to handle the value when done is true? Clearly consumers shouldn't have to be aware of whether the iterator is actually a generator and whether it ends by returning a value.

# Allen Wirfs-Brock (10 years ago)

On Apr 5, 2015, at 6:04 AM, Mark Volkmann wrote:

I thought that when an iterator returns done: true, the value should not be used.

Why do you think that? The definition of the IteratorResult interface in the the ES6 spec. doesn't say that.

However, if a generator function ends by returning a value, done will be true when that value is returned and the value should be used.

Could be used. Whether a generator or any Iterator provides a meaningful value when it reach the the 'done' state depends upon its specific definition.

Given this, how can a consumer know the correct way to handle the value when done is true? Clearly consumers shouldn't have to be aware of whether the iterator is actually a generator and whether it ends by returning a value.

An Iterator does not have to be a generator to provide a 'done' state value. In general, If you are going to do anything other than basic iteration, such as is performed by for-of, you need to know about the specific Iterator you are using.

# Guilherme Souza (10 years ago)

There is no "correct" way, it depends on the consumer logic.

The for-of construction, for instance, ignores the value when {done: true}. While x = yield* y delegation store the returned value in x.

See related discussion: esdiscuss.org/topic/proposal-generator-returning-a-value-should-throw-syntaxerror

# Mark Volkmann (10 years ago)

Thanks, that helps. I had been thinking that for-of was a model for how iterators should be consumed.

When implementing any kind of iterator (generator or not), it seems important to recognize that if you choose to return a value with done set to true, you are precluding the use of for-of with that iterator (assuming you want all the values).

# Axel Rauschmayer (10 years ago)

The only iterating mechanism that lets you access the “done value” is yield*. All other constructs (for-of, spread, destructuring, …) completely ignore it. Its main purpose is to let yield* make recursive generator calls with results, without disrupting normal yielding. That is, for normal iteration it is an out-of-band value.

# Domenic Denicola (10 years ago)

I don't think it's good to think of the value sent with done: true as "one of the values." It's in a different category, and not part of the yielded sequence.