Genarator
κ°μ²΄λ₯Ό λ°ννλ€.function* fruitList(){
yield "Banana";
yield "Apple";
yield "Orange";
}
function*
μ μ¬μ©νμ¬ ν¨μλ₯Ό μ μΈν¨.yield
ν€μλλ₯Ό μ¬μ©ν¨.Generator.prototype.next()
Generator.prototype.return()
Generator.prototype.throw()
gen.next(value)
value: generator functionμ μ λ¬ν κ°
next()
λ©μλκ° νΈμΆλλ©΄ μ λλ μ΄ν° ν¨μκ° yield
λ¬Έμ λ§λκΈ° μ κΉμ§ μ€νλλ€.value
μ done
νλ‘νΌν°λ₯Ό κ°μ§ κ°μ²΄λ₯Ό λ°ννλ€.yield
λ¬Έμ΄ λ°νν κ°(yielded value
)μ κ°λλ€.yield
λ¬Έμ μ€ν μ¬λΆλ₯Ό λνλ΄λ©° true
νΉμ false
κ°μ κ°λλ€.done
μ΄ true
μΌ κ²½μ° value
λ undefined
κ°μ κ°λλ€.next()
λ₯Ό μΈμκ°κ³Ό ν¨κ» νΈμΆν κ²½μ°, μ§νμ λ©μ·λ μμΉμ yield
λ¬Έμ μΈμκ°μΌλ‘ μΉννκ³ κ·Έ μμΉμμ λ€μ μ€ννκ² λλ€.function* fruitList(){
yield "Banana";
yield "Apple";
yield "Orange";
}
const fruits = fruitList();
fruits.next(); // {value: "Banana", done: false}
fruits.next(); // {value: "Apple", done: false}
fruits.next(); // {value: "Orange", done: false}
fruits.next(); // {value: "undefined", done: true}
next()
λ©μλμ μΈμλ₯Ό λ£μΌλ©΄ 무μλ¨.function* gen() {
while(true) {
var value = yield null;
console.log(value);
}
}
var g = gen();
g.next(1);
// "{ value: null, done: false }"
g.next(2);
// "{ value: null, done: false }"
// 2
gen.return(value)
value: λ°νλ κ°
return()
λ©μλλ μ λλ μ΄ν°λ₯Ό μ’
λ£νλ€.done: true
λ₯Ό λ°ννκ³ μΈμ κ°μ΄ μλ€λ©΄ value
μ κ·Έ κ°μ λ°ννλ€.function* gen() {
yield 1;
yield 2;
yield 3;
}
var g = gen();
g.next(); // { value: 1, done: false }
g.return("foo"); // { value: "foo", done: true }
g.next(); // { value: undefined, done: true }
done
)κ° true
λΌλ©΄ κ°μ²΄μ value
νλ‘νΌν° κ°μ κ³μ undefined
μ΄λ€.function* gen() {yield 1};
var g = gen();
console.log(g.next()); //{ value: 1, done: false }
console.log(g.next()); //{ value: undefined, done: true }
console.log(g.return(1)); //{ value: undefined, done: true }
gen.throw(exception)
{value: undefined, done: true}
λ°νcatch()
λ¬Έμμ errorλ₯Ό λ°μ μ μμfunction* gen(){
try{
yield "Trying...";
yield "Trying harder...";
yield "Trying even harder...";
}
catch(err){
console.log("Error: " + err);
}
}
const myGenrator = gen();
myGenerator.next(); // {value: "Trying...", done: false}
myGenerator.next(); // {value: "Trying harder...", done: false}
myGenerator.throw("opps");
// Error: opps
// {value: undefined, done: true}
const myPromise= () => new Promise((resolve) =>{
resolve("our value is...");
});
function* gen() {
let result = "";
yield myPromise().then(data => { result = data});
yield result + ' 2';
};
const asyncFunc = gen();
const val1 = asyncFunc.next();
console.log(val1); // {value: Promise, done: false}
val1.value.then(() => {
console.log(asyncFunc.next());
});
// {value: "our value is ...2", done: false}
μ°Έκ³