What you have to realize is what we are dealing with here are Generators; a generalized way to create custom Iterators. This article is focusing solely on using Generators for a coroutine system and doesn't elaborate on much so it might seem a bit confusing.
Here's a basic run-down:
You create a Generator Function:
function NumsUpTo100(start) {
do {
yield start;
start += 1;
} while (start < 100);
}
The thing that differentiates this from a regular Function (note: the proposed function* syntax would distinguish it visually as well) is that it actually constructs a new Generator:
var myGen = NumsUpTo100(20);
myGen now holds a Generator object. You use the arguments to initialize the state of the Generator.
Generators are Iterators, so they really shine in that respect:
for (var n in NumsUpTo100(50)){
console.log(n);
}
However, sometimes you want to manually step through iteration yourself, and you can do that by repeatedly calling .next() on your generator. It will either go forever or eventually throw StopIteration depending on how you wrote it.
AFAIK this article is actually incorrect as you have to call .next() to start the Generator before you can call .send(). Calling send() with no arguments is functionally the same as calling .next(), but last I heard it would throw an error.
The utility of .send() is sometimes during iteration you might want to send information to the generator. For example, maybe you have some sort of state machine in your generator and you want to be able to explicitly reset it's state.
Generators are very useful in general, coroutines is just one fun thing you can do with them.
Here's a basic run-down:
You create a Generator Function:
The thing that differentiates this from a regular Function (note: the proposed function* syntax would distinguish it visually as well) is that it actually constructs a new Generator: myGen now holds a Generator object. You use the arguments to initialize the state of the Generator.Generators are Iterators, so they really shine in that respect:
However, sometimes you want to manually step through iteration yourself, and you can do that by repeatedly calling .next() on your generator. It will either go forever or eventually throw StopIteration depending on how you wrote it.AFAIK this article is actually incorrect as you have to call .next() to start the Generator before you can call .send(). Calling send() with no arguments is functionally the same as calling .next(), but last I heard it would throw an error.
The utility of .send() is sometimes during iteration you might want to send information to the generator. For example, maybe you have some sort of state machine in your generator and you want to be able to explicitly reset it's state.
Generators are very useful in general, coroutines is just one fun thing you can do with them.