앞서 iterator를 사용하여 구현한 코드를 generator로 구현하면 훨씬 깔끔한 코드로 구현이 가능하다.

function* multipleGenerator(){ //function* 가 generator를 의미
    try{
        for(let i = 0; i<10; i++) {
            console.log(i);
            yield i**2;
        }
    } catch (error){    // try{} catch(error)를 통해 프로그램을 깨지 않고 Error!를 출력
        console.log(error);
    }
}
    

const multiple = multipleGenerator();
let next = multiple.next();
console.log(next.value, next.done); // 0 false

// multiple.return(); // return 하는 순간, generator가 끝남
multiple.throw('Error!'); // error를 generator에 던지는 것
next = multiple.next();
console.log(next.value, next.done); // 0 false