美文网首页
Generator function基于Promise对象的自动

Generator function基于Promise对象的自动

作者: 并肩走天涯 | 来源:发表于2016-08-24 17:40 被阅读91次
      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);
      });
    });
    

    相关文章

      网友评论

          本文标题:Generator function基于Promise对象的自动

          本文链接:https://www.haomeiwen.com/subject/xtjosttx.html