generator함수는 다음과 같은 표현식을 사용하여 선언한 함수를 의미한다.
generator함수를 호출하면 generator객체를 생성하여 반환한다. 일반적으로 함수를 호출하면, {} 이 실행되지만, generator함수는 {}를 실행하지 않고, generator객체를 생성하여 반환한다.function* 함수명 (){}
generator함수는 generator객체를 생성하여 반환한다.
<script type="text/javascript">
function* a() {
console.log('1');
}
const x = a(); //generator객체
console.log(typeof a); // function
console.log(typeof x); // object
</script>
<script type="text/javascript">
function* a() {
console.log('1');
console.log('2');
console.log('3');
}
const x = a(); //generator객체
// console.log(typeof a); // function
console.log(typeof x); // object
x.next(); // next를 명시하지 않으면 generator함수 내의 코드를 실행하지 않음
//1
//2
//3
</script>
<script type="text/javascript">
function* a() {
console.log('1');
yield console.log('2');
console.log('3');
}
const x = a(); //generator객체
x.next(); // next를 명시하지 않으면 generator함수 내의 코드를 실행하지 않음
// 1
// 2
console.log('========');
x.next();
// 3
</script>
done의 의미는 함수 내 실행문이 끝까지 실행되었는지 안되었는지로 이해하자!
<script type="text/javascript">
function* a(n, n2) {
console.log('1');
yield n + n2;
yield '곰돌이';
console.log('3');
}
const fna = a(10, 20);
console.log(fna); // 1
console.log(fna.next()); // {value:30, done:false}
console.log(fna.next()); // {value:"곰돌이", done:false}
</script>
3은 출력이 안된다.
.next는 yield단위로 수행된다.
<script type="text/javascript">
function* a(k, k2) {
console.log('1');
yield k + k2;
yield '홍길동';
console.log('end');
}
const x = a(10, 20); // 1
console.log(x.next()); // {value:30, done:false}
console.log(x.return()); // 강제 종료 {value:undefined, done:true}
console.log(x.next()); // {value:undefined, done:true}
</script>
<script type="text/javascript">
function* a() {
const aaa = yield 'A';
const bbb = yield 'B';
console.log(aaa, bbb);
}
const x = a();
console.log(x.next()); // {value:"A", done: false}
console.log(x.next(2000)); // {value:"B", done:false}
console.log(x.next(3000)); //2000,3000
// {value:undefined, done:true}
</script>