试图“屈服”到`co(fn).call`

时间:2014-02-20 09:41:48

标签: javascript node.js generator ecmascript-harmony 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 );

2 个答案:

答案 0 :(得分:0)

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

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

否则链条会停止,gah

答案 1 :(得分:0)

你试图实现的目标并不十分清楚,但我认为你想看到

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相同。