Promise 객체 기반 Generator function 자동 실행

2321 단어
  var fs = require('fs');

  var readFile = function ( fileName ) {
    return new Promise(function ( resolve, reject ) {
      fs.readFile(fileName, function ( err, data ) {
        if (err) {
          return reject(err);
        }

        return resolve(data);
      });
    });
  };

  var gen = function* () {
    var f1 = yield readFile('/etc/fstab');
    var f2 = yield readFile('/etc/shells');
    console.log(f1.toString());
    console.log(f2.toString());
  };

  /*
  g.next().value.then(function ( data ) {
    g.next(data).value.then(function ( data ) {
      g.next(data);
    });
  });
  */

  var run = function () {
    let g = gen();

    let next = function ( data ) {
      let result = g.next(data);
      if (result.done) {
        return  result.value;
      }

      result.value.then(function (data) {
        next(data);
      });
    };

    next();
  };

  run(gen);

// spawn 
var spawn = function ( genFunc ) {
    return new Promise(function ( resolve, reject ) {
        let g = genFunc();

        let next = function (nextFunc) {
            try {
                let nextF = nextFunc();

                if (nextF.done) {
                    return resolve(nextF.value);
                }

                Promise.resolve(nextF.value)
                    .then(
                        function ( v ) {
                            next(function () {
                                return g.next(v);
                            });
                        },
                        function ( e ) {
                            next(function () {
                                return g.throw(e);
                            });
                        });
            } catch (e) {
                return reject(e);
            }
        };

        next(function () {
            // return g.next(undefined);
            return g.next();
        });
    });
};

spawn(gen)
    .then(function () {
        console.log("function success ...");
    })
    .catch(function ( e ) {
        console.log(e);
    });

Generator 함수를 수동으로 실행하는 것은then 방법으로 겹겹이 리셋 함수를 추가하는 것입니다.
var g = gen();
g.next().value.then(function ( data ) {
  g.next(data).value.then(function ( data ) {
    g.next(data);
  });
});

좋은 웹페이지 즐겨찾기