728x90
1. Generator (feat. yield)
- 함수의 실행을 중간에 멈췄다가 다시 실행할 수 있다.
- 여러 값을 필요에 따라 하나씩 반환할 수 있다.
- function* : 이렇게 function 오른쪽에 * 을 붙여서 만든다.
- 내부에 yield 키워드를 사용하여 함수의 실행을 멈출 수 있다.
- generator 실행하면 코드가 실행되는게 아니라 generator 객체가 반환됨
// generator yield next
function* fn1(){
console.log(1)
yield 1;
console.log(2)
yield 2;
console.log(3)
console.log(4)
yield 3;
return "finish";
}
const test = fn1();
console.log(test);
Object [Generator] {}
- Generator 특징
1) 미리 값을 만들어 두지 않음 (필요할 때만 만들어 줌, next 할때만 하나씩 던져 줌)
2) 반복이 가능
3) 외부로부터 값을 입력받을 수도 있음.
4) 다른 작업하다가 다시와서 next() 하면 마지막 부분 이어서 진행
2. Generator의 실행 (generator 안에서 쓸 수 있는 메소드)
1) next() : 실행할때마다 다음 yield 전까지 값을 반환함
- next는 기본적으로 하나씩, 한 단위씩 가져옴
- 사용: genetator함수가 담긴 변수명.next();
- value: 값, done: true || false 를 반환함
- 다음 yield를 만날때까지 값을 반환 함
- 더이상 반환할 값이 없으면 true 그 전까진 다 false == 다나왔니? 의 의미
// generator yield next
function* fn1(){
console.log(1)
yield 1;
console.log(2)
yield 2;
console.log(3)
console.log(4)
yield 3;
return "finish";
}
const test = fn1();
console.log(test.next());
console.log(test.next());
console.log(test.next());
console.log(test.next());
1 // 1반환하고 멈춤
{ value: 1, done: false }
2 // 그 다음 2반환하고 멈춤
{ value: 2, done: false }
3
4 // 그 다음 3,4반환하고 멈춤
{ value: 3, done: false }
{ value: 'finish', done: true } // 그 다음 yield가 없어 true 반환 ( 더이상 뱉을게 없어)
2) return() : 즉시 반환, 끝내기
- 함수를 담은 변수명.retun("이 값을 벨류로 반환하고 끝남")
// generator return
function* fn1(){
console.log(1)
yield 1;
console.log(2)
yield 2;
console.log(3)
console.log(4)
yield 3;
return "finish";
}
const test = fn1();
console.log(test.next())
console.log(test.return("return해"))
console.log(test.next());
1
{ value: 1, done: false }
{ value: 'return해', done: true } // return 을 뱉고 true
{ value: undefined, done: true } // 그 다음 next 찍어도 이미 다 뱉은 걸로 나오고 true
3) throw() : 에러를 호출함
- throw(new Error("에러문구")) 와 함께 써야 함.
// generator throw
function* fn1(){ // try + catch 로 감싸서 이 함수의 오류상황을 대응할 수 있도록 함
try{console.log(1)
yield 1;
console.log(2)
yield 2;
console.log(3)
console.log(4)
yield 3;
return "finish"}
catch(err){console.log(err)}
}
const test = fn1();
console.log(test.next())
console.log(test.throw(new Error("throw로 에러 만들어"))) // throw 메소드에 new Error
console.log(test.next());
1
{ value: 1, done: false }
Error: throw로 에러 만들어 // 에러 나오고
{ value: undefined, done: true } // 없는 값 반환하고 true로 전환 (다뱉었다)
{ value: undefined, done: true } // 그 다음 next도 없는 값에 true 전환
728x90
'html,css,js' 카테고리의 다른 글
[HTML 기초] 마크업, element 요소, attribute 속성, w3c 웹표준 (0) | 2023.05.17 |
---|---|
[자바스크립트 기초] 계산기 만들기 calculator (0) | 2023.05.16 |
[자바스크립트 기초] if 조건문, or and not 논리 연산자 (0) | 2023.05.16 |
[자바스크립트 중급] async, await (Promise 가독성 높히기) try & catch (0) | 2023.05.16 |
[자바스크립트 중급] Promise // then, catch, finally, Promise.all, Promise.race (0) | 2023.05.15 |