[JavaScript] yield and yield*
yield
The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller.
It can be thought of as a generator-based version of the return keyword.
Calling a generator function constructs a Generator object. Each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of the following:
- A yield expression. In this case, the generator pauses, and the next() method return an iterator result object with two properties: value and done. The value property is the value of the expression after the yield operator, and done is false, indicating that the generator function has not fully completed.
- The end of the generator function. In this case, execution of the generator ends, and the next() method returns an iterator result object where the value is undefined and done is true.
- A return statement. In this case, execution of the generator ends, and the next() method returns an iterator result object where the value is the specified return value and done is true.
- A throw statement. In this case, execution of the generator halts entirely, and the next() method throws the specified exception.
Example of yield
function* countAppleSales() {
const saleList = [3, 7, 5];
for (const sale of saleList) {
yield sale;
}
}
const appleStore = countAppleSales(); // Generator { }
console.log(appleStore.next()); // { value: 3, done: false }
console.log(appleStore.next()); // { value: 7, done: false }
console.log(appleStore.next()); // { value: 5, done: false }
console.log(appleStore.next()); // { value: undefined, done: true }
yield*
The yield* operator can be used within generator functions to delegate to another iterable object, such as a Generator.
Example of yield*
function* g1() {
yield 2;
yield 3;
yield 4;
}
function* g2() {
yield 1;
yield* g1();
yield 5;
}
const gen = g2();
console.log(gen.next()); // {value: 1, done: false}
console.log(gen.next()); // {value: 2, done: false}
console.log(gen.next()); // {value: 3, done: false}
console.log(gen.next()); // {value: 4, done: false}
console.log(gen.next()); // {value: 5, done: false}
console.log(gen.next()); // {value: undefined, done: true}
0 댓글