繁体   English   中英

试图将`yield`到`co(fn).call`

[英]Trying to `yield` to a `co( fn ).call`

在更改上下文值时,让co继续执行时遇到问题:

var co = require( 'co' );

function *foo( next ){
    console.log( 'foo yielding' );
    yield next;
    console.log( 'foo yielded' );

    return 42;
}

var bar = co( function *(){
    console.log( 'bar yielding' );

    // this is the bit that I'm having problems with
    yield function( cb ){    
        return co( foo ).call(
              { name: 'this object' }
            , function(){ console.log( 'in next' ); }
            , cb
        );
    };

    console.log( 'bar yielded' );
} );

bar();

上面的日志:

bar yielding
foo yielding
in next

我试过将co( foo ).call行包装在一个函数,一个生成器函数以及许多其他东西中。 我无法正常工作...帮助!

请注意,如果我正常打电话给co ,它会起作用。 但是,然后我无法设置要尝试调用的函数的上下文或将参数传递给该函数:

yield co( foo );

我的下一个函数需要一个回调,并且需要执行它:

, function( cb ){ console.log( 'in next' ); cb(); }

否则链会停止,嘎

尚不清楚您要实现什么目标,但我想您想看看

bar yielding
foo yielding
in next
foo yielding
bar yielding

试试这个代码:

var co = require( 'co' );

function *foo( next ){
    console.log( 'foo yielding' );
    yield next;
    console.log( 'foo yielded' );

    return 42;
}

var bar = co( function *(){
    console.log( 'bar yielding' );

    // this is the bit that I'm having problems with
    yield co( foo ).bind(
              { name: 'this object' }
            , function(cb){ console.log( 'in next, name: ' + this.name ); process.nextTick(cb) }
        );

    console.log( 'bar yielded' );
} );

bar();

几个脚注:

  • 如果产生一个函数,则认为它是一个thunk,也就是说,它接受一个参数并且是回调;
  • 您需要调用此回调,异步进行也是一个好主意;

将其应用到您的代码中:-产生一个函数,但不要调用它的cb参数; -与next相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM