nodejs之yield 和 yield*

1.普通的yield

function* outer(){

    yield 'begin';
    yield inner();
    yield 'end';
}

function* inner(){

    yield 'inner';

}


var it = outer(),v;

v= it.next().value;

console.log(v);

v= it.next().value;

console.log(v);
console.log(v.toString());

v = it.next().value;

console.log(v);

输出

➜  qiantou node yiely02.js
begin
{}
[object Generator]
end

2.代理yield

➜  qiantou cat yield05.js 
function* outer(){
    yield 'begin';

    var ret = yield* inner();

    console.log(ret);

    yield 'end';

}


function * inner(){

    yield 'inner';

    return 'return from inner';

}

var it = outer(),v;

v = it.next().value;

console.log(v);


v = it.next().value;

console.log(v);


v = it.next().value;

console.log(v)

输出

➜  qiantou node yield05.js 
begin
inner
return from inner
end

yield* 后面接受一个 iterable object 作为参数,然后去迭代(iterate)这个迭代器(iterable object),同时 yield* 本身这个表达式的值就是迭代器迭代完成时(done: true)的返回值。调用 generator function 会返回一个 generator object,这个对象本身也是一种 iterable object,所以,我们可以使用 yield* generator_function() 这种写法。
yield 是为了解决 node.js 异步回调问题,主要是写法上的同步

3.yield 和 co

➜  qiantou cat co01.js 
var co = require('co');
co(function* (){

    var a = yield Promise.resolve(1);

    console.log(a);

    var b = yield later(10);

    console.log(b);

    var c = yield fn;
    console.log(c);

    var d = yield fn(5);

    console.log(d);

    var e = yield [
        Promise.resolve('a'),
        later('b'),
        fn,
        fn(5)
    ];

    console.log(e);

var f = yield{
    'a':Promise.resolve('a'),
    'b':later('b'),
    'c':fn,
    'd':fn(5)
};

console.log(f);

function* fn(n){
    n = n || 1;

    var a = yield later(n);

    return 'fn_'+ a;


}

function later(n,t){

    t = t || 1000;

    return function(done){
        setTimeout(function(){done(null,n)},t);

    };

}


}).catch(function(e){
    console.error(e);

});

输出

➜  qiantou node co01.js
1
10
fn_1
fn_5
[ 'a', 'b', 'fn_1', 'fn_5' ]
{ a: 'a', b: 'b', c: 'fn_1', d: 'fn_5' }

yield* 的作用

用原生语法,抛弃 co 的黑魔法,换取一点点点点性能提升
明确表明自己的意图,避免混淆
调用时保证正确的 this 指向
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值