Generator Functions를 사용하면 함수가 종료되고 나중에 다시 시작될 때 사이에 코드를 실행할 수 있습니다. 따라서 생성기를 사용하여 코드에서 흐름 제어를 관리할 수 있습니다. 언제든지 실행을 일시 중지할 수 있으므로 비동기 작업을 쉽게 취소할 수 있습니다.
구문은 다음과 같습니다. "function" 키워드 뒤에 별표를 추가하는 것을 잊지 마십시오. 다음 중 하나를 사용하여 별표를 추가할 수 있습니다. -
function *myFunction() {}
// or
function* myFunction() {}
// or
function*myFunction() {} 예시
제너레이터 함수를 사용하는 방법을 살펴보겠습니다.
라이브 데모
<html>
<body>
<script>
function* display() {
var num = 1;
while (num < 5)
yield num++;
}
var myGenerator = display();
document.write(myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
</script>
</body>
</html>