码迷,mamicode.com
首页 > 其他好文 > 详细

ES6之Generator

时间:2017-10-21 19:00:12      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:api   方法   函数名   als   语法   错误   遍历   es6   app   

  Generator函数是一种异步编程解决方案,再次叙述他的语法和API,至于异步编程请看后续文章。

  Generator本身自带Iterator接口,所以可以使用for...of,个人理解为Generator是一个指针代码块,里面封装了指针,使用next()就开始执行指针所指向的函数。这个函数有两个特征:一是function命令与函数名之间有一个*号,二是函数体内部使用yield语句定义不同的内部状态。

function* sayhi() { 
    yield ‘this‘; 
    yield ‘is‘; 
    yield ‘Generator‘; 
    return ‘加载完毕‘;        //return方法返回最终给定的值并终结Generator函数的遍历
}
for(let g of sayhi()){ 
    console.log(g);         //this is Generator
} 
var hi = sayhi(); 
    console.log(hi.next());         //{ value: ‘this‘, done: false }
console.log(hi.next());         //{ value: ‘is‘, done: false }
console.log(hi.next());         //{ value: ‘Generator‘, done: false }
console.log(hi.next());        //{ value: ‘加载完毕‘, done: true }
/* 当然Generator那个*号有4种写法 比如  function* functionName 或者是 function * functionName或者是function *functionName再或者是function*functionName当然这玩意是自己怎么写开心就怎么写*/

  yield在这里面可以理解为就是指针指向某些函数或者值,yield语句就是暂停标志他只能用在Generator函数里面不能用在普通函数内部,如果yield语句用在一个表达式中,必须放在()里面。Generator函数只有使用next()才可以使他接着向下走,如果在Generator不用yield那么就会变成了一个暂缓函数,只有next()才开始执行该函数,单纯的调用没什么用。如果要在一个Generator里面调用另一个Generator,那么就得使用*号,例如function* a(){ yield* b() } function* b(){}

  next()方法可以带一个参数,该参数会被当做上一条yield语句的返回值,但是第一次使用next()不能带参数,因为V8引擎会直接忽略第一次使用next方法时的参数,如果非要用可以在Generator函数外面再包一层。

function wrapper(generatorFunction) { 
    return function (...args) { 
        let generatorObject = generatorFunction(...args); 
                          generatorObject.next(); 
        return generatorObject; 
    }; 
} 
const wrapped = wrapper(function* () { 
    console.log(`第一次输入的是:${yield}`);    //第一次输入的是:hello 
    return ‘DONE‘; 
}); 
console.log(wrapped().next(‘hello‘));            //{ value: ‘DONE‘, done: true }    

  Generator函数返回的遍历器对象都有一个throw方法,可以在函数体外抛出错误,然后在Generator函数体内捕获,注意throw方法不等于throw命令,throw命令抛出的异常只能被函数体外的catch语句捕获,而throw方法能在函数内部或者函数外部捕获异常。

var g = function *() { 
    while(true){ 
        try{ 
            yield; 
    }catch(e){ 
        if(e != ‘a‘) throw e ; 
        console.log(‘内部捕获‘,e);    //内部捕获 a
    }     
    } 
}; 
var i = g(); 
i.next(); 
try{ 
    i.throw(‘a‘); 
    i.throw(‘b‘); 
}catch(e){ 
    console.log(‘外部捕获‘,e);             //内部捕获 b
}

 

 

    

ES6之Generator

标签:api   方法   函数名   als   语法   错误   遍历   es6   app   

原文地址:http://www.cnblogs.com/qiaohong/p/7705242.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!