generator
함수의 실행을 중간에 멈췄다가 재개할 수 있다
function* fn() {
yield 'a';
yield 'b';
yield 'c';
};
const a = fn();
console.log(a.next());
console.log(a.next());
console.log(a.next());
// 출력결과
> Object { value: "a", done: false }
> Object { value: "b", done: false }
> Object { value: "c", done: false }
즉시 done 값이 true가 됨
에러 처리용
generator는 iterator이면서 iterable 객체
function* fn() {
const num1 = yield "첫번째 숫자";
console.log(num1);
const num2 = yield "두번째 숫자";
console.log(num2);
return num1 + num2;
}
const a = fn();
a.next();
>> {value: "첫 번째 숫자", done: false}
a.next(5);
>> 5
>> {value: "두 번째 숫자", done: false}
a.next(7);
>> 7
>> {value: 12, done: false}
function* fn() {
let index = 0;
while (true) {
yield index++;
}
}
const a = fn();
a.next();
>> {value: 0, done: false}
a.next();
>> {value: 1, done: false}
a.next();
>> {value: 2, done: false}
yield*
다른 generator를 불러온다
function* gen1() {
yield "W";
yield "o";
yield "r";
yield "l";
yield "d";
}
function* gen2() {
yield "Hello,";
yield* gen1();
yield "!";
}
console.log(...gen2());
>> Hello, W o r l d !
정리
generator는 다른 작업을 하다가 다시 돌아와서 next() 해주면 진행이 멈췄던 부분부터 이어서 실행한다.