Generator 函数

ES6 新引入了 Generator 函数,可以通过 yield 关键字,把函数的执行流挂起,为改变执行流程提供了可能,从而为异步编程提供解决方案。

Generator 有两个区分于普通函数的部分:

 一:是在 function 后面,函数名之前有个 * ;

 二:函数内部有 yield 表达式。

 下面通过一个小demo演示下Generator 函数的用法

// 定义一个fun生成器函数
    function* fun() {
        console.log("one");
        yield '1';
        console.log("two");
        yield '2';
        console.log("three");
        return '3';
    }
    // Generator 函数的执行机制与普通函数的执行机制不同,它不会立即执行,并且要通过迭代器的next方法才能调用函数内部的值

    var f = fun();
     f.next();//one
     f.next();//two
    // 第一次调用 next 方法时,从 Generator 函数的头部开始执行,先是打印了 one ,执行到 yield 就停下来,并将yield 后边表达式的值 '1',作为返回对象的 value 属性值,此时函数还没有执行完, 返回对象的 done 属性值是 false。
    // 第三次调用 next 方法时, 此时函数已经执行完了,所以返回 value 属性值是 undefined ,done 属性值是 true 。

        

 return 方法返回给定值,并结束遍历 Generator 函数。

 return 方法提供参数时,返回该参数;不提供参数时,返回 undefined 。

 function* foo() {
        yield 1;
        yield 2;
        yield 3;
    }
    var f = foo();
     console.log(f.next()); // {value: 1, done: false}
     console.log(f.return("foo"));// {value: "foo", done: true}

throw 方法可以再 Generator 函数体外面抛出异常,再函数体内部捕获。

   var g = function* () {
        try {
            yield;
        } catch (e) {
            console.log('catch inner', e);
        }
    };

    var i = fun();
    i.next();
    try {
        i.throw('a');
        i.throw('b');
    } catch (e) {
        console.log('catch outside', e);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值