Today I Learned
[Javascript] 자주 까먹는 generator
떼굴펜
2024. 5. 10. 18:02
함수 선언시 function* (){}와 같이 *을 붙여서 선언한다. 함수 내부에서 yield가 있을 때마다 멈추고 대기 상태가 되며, next가 실행될 때마다 대기하던 yield를 지나쳐 실행된다.
var addCoffee = function (name) {
return new Promise(resolve => {
setTimeout(() => {
coffeMaker.next(prevName ? `${prevName}, ${name}` : name;
}, 500);
});
}
var coffeGenerator = function* () {
const espresso = yield addCoffee("", "에스프레소");
console.log(espresso); // 에스프레소
const americano = yield addCoffee(espresso, "아메리카노");
console.log(americano); // 에스프레소, 아메리카노
const mocha = yield addCoffee(americano, "카페모카");
console.log(mocha); // 에스프레소, 아메리카노, 카페모카
const latte = yield addCoffee(mocha, "카페라떼");
console.log(latte); // 에스프레소, 아메리카노, 카페모카, 카페라떼
};
var coffeMaker = coffeGenerator();
coffeMaker.next();