Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

javascript - Delegated yield (yield star, yield *) in generator functions

ECMAScript 6 should be bringing generator functions and iterators. A generator function (which has the function* syntax) returns an iterator. The iterator has a next method which, when repeatedly called, executes the body of the generator function, repeatedly pausing and resuming execution at every yield operator.

The ECMAScript 6 wiki on generators also introduces the "delegated yield" yield* operator as follows:

The yield* operator delegates to another generator. This provides a convenient mechanism for composing generators.

What does "delegate to another generator" mean? How can I use yield* to "conveniently compose generators"?

[You can play with generators in Node v0.11.3 with the --harmony-generators flag.]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Delegating to another generator means the current generator stops producing values by itself, instead yielding the values produced by another generator until it exhausts it. It then resumes producing its own values, if any.

For instance, if secondGenerator() produces numbers from 10 to 15, and firstGenerator() produces numbers from 1 to 5 but delegates to secondGenerator() after producing 2, then the values produced by firstGenerator() will be:

1, 2, 10, 11, 12, 13, 14, 15, 3, 4, 5

function* firstGenerator() {
    yield 1;
    yield 2;
    // Delegate to second generator
    yield* secondGenerator();
    yield 3;
    yield 4;
    yield 5;
}

function* secondGenerator() {
    yield 10;
    yield 11;
    yield 12;
    yield 13;
    yield 14;
    yield 15;
}

console.log(Array.from(firstGenerator()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...