[실전 자바스크립트] 제너레이터

주수호·2022년 5월 17일
0

제너레이터

함수의 실행을 중간에 멈추고 재개 할 수 있는 기능을 말합니다.

function* f1() {
  	console.log('f1-1')
    yield 10;
  	console.log('f1-2');
    yield 20;
  	console.log('f1-3');
    return 'finished';
}

const gen = f1(); //*함수와 gen객체를 빈환함
console.log(gen.next()); // 다음 yield코드가 실행되기 전까지 진행 됨.
console.log(gen.next()); // 다음 yield코드가 실행되기 전까지 진행 됨.
console.log(get.return('abc')) // { value: 'abc', done: true }
console.log(gen.next()); // 다음 yield코드가 실행되기 전까지 진행 됨. { value: 'finished', done: true }

// 이후 호출은 되면 done은 true가 됩니다.


// 이런식으로 제너레이터에 throw함수를 호출하면 try catch에서 해당 
console.log(gen.throw('some error'));

결과값은

{ value: 10, done: false } 기본적인 제너레이터의 출력값입니다.

이런식으로 나타나게 됩니다.

return 키워드가 호출이 되어지는 경우, done이 True로 변경되게 됩니다.

제너레이터는 함수를 생성하여 next를 호출하면서 그 처리가 진행되어지게 됩니다.

이는 제너레이터가 iterator라는 뜻입니다.

profile
항상 준비하는 엔지니어

0개의 댓글