Javascript 试图“屈服”于“co(fn).呼叫`

Javascript 试图“屈服”于“co(fn).呼叫`,javascript,node.js,generator,ecmascript-harmony,co,Javascript,Node.js,Generator,Ecmascript Harmony,Co,在更改co的上下文值时,我在恢复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' ); //

在更改co的上下文值时,我在恢复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,也就是说,它接受一个参数,它是callback
  • 您需要调用这个回调,异步调用也是一个好主意
将此应用于您的代码: -您生成一个函数,但从不调用它的
cb
参数; -与
next
相同