'Generator'에 해당되는 글 1건

  1. 2022.03.21 Generator

Generator

개발 및 관리/Javascript 2022. 3. 21. 23:19 posted by HighLighter
반응형

Generator : 함수와 실행을 중간에 멈췄다가 재개할 수 있는 기능

function* fn() {
  console.log(1);
  yield 1;
  console.log(2);
  yield 2;
  console.log(3);
  console.log(4);
  yield 3;
  return "finish";
}

const a = fn();

a
a.next();

-------------------------------------------------------------------

Generator : 함수의 실행을 중간에 멈췄다가 재개할 수 있는 기능

next(), return(), throw()

-------------------------------------------------------------------

a.next();

a.return(`END`);

a.next();

function* fn() {
 try{
  console.log(1);
  yield 1;
  console.log(2);
  yield 2;
  console.log(3);
  console.log(4);
  yield 3;
  return "finish";
 } catch (e) {
  console.log(e);
 }
}

const a = fn();

a.next();
a.next();

a.throw(new Error('err'));

a.next();

-------------------------------------------------------------------

iterable
 - Symbol.iterator 메소드가 있다.
 - Symbo.iterator 는 iterator를 반환해야 한다.

iterator
 - next 메서드를 가진다.
 - next 메서드는 value와 done 속성을 가진 객체를 반환한다.
 - 작업이 끝나면 done은 true가 된다.

-------------------------------------------------------------------

const arr = [1, 2, 3, 4, 5];
const it = arr[Symbol.iterator]();
it.next();
it.next();
it.next();
it.next();
it.next();

for(let num of arr) {
  console.log(num)
};


-------------------------------------------------------------------

function* fn() {
  yield 4;
  yield 5;
  yield 6;
}

const a = fn();

a[Symbol.iterator]() === a;

for(let num of a) {
  console.log(num);
}

const str = 'hello';
str[Symbol.iterator]

const xx = str[Symbol.iterator]()

xx.next();

for(let num of xx) {
  console.log(num);
}

-------------------------------------------------------------------

Generator : next()에 인수 전달

function* fn() {
  const num1 = yield "첫번째 숫자를 입력해주세요";
  console.log(num1);

  const num2 = yield "두번째 숫자를 입력해주세요";
  console.log(num2);

  return num1 + num2;
}

const a = fn();

a.next();
a.next(2);
a.next(4);

-------------------------------------------------------------------

Generator : 값을 미리 만들어 두지 않음, 값을 필요할 때 마다 그때 그때 만든다. 필요한 순간까지 계산을 미룰 수 있다.

function* fn() {
  let index = 0;
  while (true) {
    yield index++;
  }
}

const a = fn();
a.next();

-------------------------------------------------------------------

Generator : yield* 을 이용하여 다른 Generator 호출

function* gen1() {
  yield "W";
  yield "o";
  yield "r";
  yield "l";
  yield "d";
}

function* gen2() {
  yield "Hello,";
  yield* gen1();
  yield "!";
}

console.log(...gen2());

-------------------------------------------------------------------

Generator : 제너레이터는 다른 작업을 하다가 다시 돌아와서
next() 해주면 진행이 멈췄던 부분 부터 이어서 실행

ex) Redux Saga

반응형