Front/JavaScript
[JavaScript] Generator Function 이해하기
Awesome-SH
2020. 5. 25. 15:18
Generator Function
GeneratorFunction
GeneratorFunction 생성자는 새로운 generator function 객체를 생성한다. JavaScript 에서 모든 generator function 은 실제로 GeneratorFunction object 이다.
developer.mozilla.org
Generator Function을 처음 알게 된건, Redux-saga를 통해 알에 되었다
모양은 function* 이렇게 function 선언 다음에 * 가 붙은 모양이다.
function* generatorTest() {
yeild console.log(5);
yeild console.log(10);
}
일반 함수는 함수를 호출하면 Funtion안에 선언된 로직들이 일괄 실행 되는데에 반해,
Generator Function 은 Yield와 Next를 통해 로직을 정지시킬수 있으며, 다시 시작 시킬 수도 있다
Generator는 Itorator 객체를 반환한다.
yield & next
yield는 함수의 실행을 일시적으로 막는 것 ( 일반함수의 return 과 유사 )
next는 다음 진행을 재개시키는 것
Generator Function Return
return 수행 후 > Iterator 종료 > return 뒤에 오는 값
> IteratorResult 객체의 value 프로퍼티에 할당, done 프로퍼티는 Boolean값이 할당
예제)
function* testGenerator() {
return 'Hello';
}
const gen = testGenerator();
console.log(gen.next());
// { value : 'Hello', done: true }
Generator를 사용한 라이브러리들은 어떤게 있을까?
- 비동기 처리를 위한 리덕스 미들웨어 Redux Saga
- Node.js 프레임워크 중 Koa
등이 있다.