Why should I use a generator function?

Jerry jones's icon

Ok so I started looking at these fancy new generator functions. They seem cool, I guess, but my big challenge is understanding WHY. Everything I've heard is that generators help with async code, but I guess I'm having a hard time seeing where a generator would be better than just using a promise or async/await. Could someone give me some suggestions.

jay po's icon

Generator functions are more closely related to for loops than async.
Key difference is the yield keyword.
This is like a bookmark, returning the value from the function, then resuming from that point when called again.

Heres an (untested) example. Notice how our iterator is potentially infinite?

function* RandomGenerator(from, toInclusive) {
    const range = toInclusive - from;
    while(true) {
        yield from + (random() % range);
    }
}
const randoms = RandomGenerator(1, 10);
for(var random of randoms) {
    console.log(random);
    if(random === 5) break;
}