728x90
이터레이터를 조금 더 간편한 방식으로 만들 수 있게 해줍니다.
// 제너레이터를 만들기 위해서는 함수를 만들어야 하는데 이때 *를 같이 입력해야합니다.
function* multipleGenerator(){
try{
for(let i = 0; i < 10; i++){
// 사용자가 next를 사용할 때까지 기다렸다가 하나하나씩 리턴해줍니다.
// 즉 사용자가 next를 호출해줘야 i는 0에서 1로 증감한다.
yield i ** 2
}
} catch(err){
console.log(err)
}
}
const multiple = multipleGenerator
let next = multiple.next()
console.log(next)
next = multiple.next()
console.log(next)
// return을 하는 순간 제너레이터가 종료가 된다.
multiple.return()
// multiple안으로 error를 던지는 것
multiple.throw('Error!')
// 오류가 발생
next = multiple.next()728x90
'프론트엔드 > 자바스크립트' 카테고리의 다른 글
| 프로토타입 (Prototype) (0) | 2022.04.24 |
|---|---|
| 이터레이션(이터러블) (0) | 2022.04.20 |
| 이터러블 (0) | 2022.04.04 |
| Inheritance (0) | 2022.03.31 |
| Getter & Setter (0) | 2022.03.30 |