generator base

javascript¿¡ generator¶ó´Â °ÍÀÌ ÀÖ´Ù.
óÀ½¿¡´Â "ÀÌ°Ô ¸ð¾ß!!!"  »ý°¢ Çϸç, ¹¹ ÇÏ´Â °ÍÀÎÁö ¸ô¶ú´Ù.

¹Ýº¹ÀÚ¸¦ ±¸Çö ÇÒ·Á¸é [Symbol.iterator]()¿Í .next() ¸Þ¼Òµå¸¦ ±¸ÇöÇØ¾ß ÇÏÁö¸¸, Á¦³Ê·¹ÀÌÅ͸¦ »ç¿ëÇϸé Iterable, Iterator¸¦ ½±°Ô ±¸Çö ÇÒ¼ö ÀÖ´Ù.

Á¦³Ê·¹ÀÌÅÍÀÇ ±âº»

¿¹Á¦¸¦ ¸ÕÀú »ìÆ캸°í ÇÔ¼ö¸¦ ¼³¸íÇÑ´Ù.

function* generator() {
  yield 1;
  yield 2;
  yield 3;
}

var gen = generator();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

/*
À§¿Í µ¿ÀÏÇÑ °á°úÀÌ´Ù.
for(const val of generator()) {
  console.log(val);
}
*/

ÇÔ¼ö ¼±¾ð : function*·Î ½ÃÀÛ
Á¦³Ê·¹ÀÌÅÍ ½ÇÇà: next()
°á°ú: value·Î ¾ò¾î¿Â´Ù.
ÁøÇà »óÅÂ : done
°ª ¹Ýȯ : yield·Î  ¹Ýȯ

°´Ã¼ ÇÁ·ÎÆÛƼ¿¡¼­ sleep ÇÑÈÄ ½ÇÇà

Á¦³Ê·¹ÀÌÅ͸¦ »ç¿ëÇØ À¯´ÏƼÀÇ ÄÚ·çƾÀ» Èä³»³» º¸ÀÚ.
¿øÇÏ´Â ½Ã°£ ¸¸Å­ Sleep ÇÑÈÄ¿¡ ´Ù½Ã ½ÇÇà ÇÒ °ÍÀÌ´Ù.

function *myGenerator() {
}

var my= {
    self,
    func :
    function*(){
        console.log('my start');
        setTimeout(()=> { self.next(); }, 3000);
        yield 3;
        console.log('my later 3 sec');
        setTimeout(()=> { self.next(); }, 1000);
        yield 1;
        console.log('my later 1 sec');
        setTimeout(()=> { self.next(); }, 2000);
        yield 2;
        console.log('my later 2 sec');
    },
    exec: function() {
        self = this.func();
        self.next();
    }
};

my.exec();

Ŭ·¡½º¿¡¼­ sleep ÇÑÈÄ ½ÇÇà

°´Ã¼ ÇÁ·ÎÆÛƼ ¿¹Á¦¸¦ Ŭ·¡½º¿¡¼­ »ç¿ë ÇÒ¼ö ÀÖ´Â ¿¹Á¦·Î º¯È¯ ÇÏ¿´´Ù.

class Npc {
    constructor(){
        this.workGen = this.work();
    }
   
    runStep1() {
        console.log(this, 'Npc Step1 3sec');
    }
   
    runStep2() {
        console.log(this, 'Npc Step2 3sec');
    }
    sleep(sec) {
        setTimeout(()=> { this.workGen.next(); }, sec*1000);
    }
   
    * work(){
        console.log('Npc start');
        this.sleep(3);
        yield 3;
        this.runStep1();
        this.sleep(2);
        yield 2;
        this.runStep2();
    }
   
    run(){
        this.workGen.next();
    }
}

let npc = new Npc();
npc.run();

ÂüÁ¶)
http://hacks.mozilla.or.kr/2015/08/es6-in-depth-generators/
https://thejsguy.com/2016/10/15/a-practical-introduction-to-es6-generator-functions.html