0

I'm having a problem getting co to resume when also changing it's context value:

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();

The above logs:

bar yielding
foo yielding
in next

I've tried wrapping the co( foo ).call line in a function, a generator function, and a bunch of other things. I can't get it to work... help!

Note that if I call co normally, it works. But then I can't set the context of, or pass arguments to, the function I'm trying to call:

yield co( foo );
Mark Kahn
  • 81,115
  • 25
  • 161
  • 212

2 Answers2

0

My next function needed a callback, and it needs to execute it:

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

otherwise the chain gets halted, gah

Mark Kahn
  • 81,115
  • 25
  • 161
  • 212
0

It's not quite clear what you try to achieve, but I assume you want to see

bar yielding
foo yielding
in next
foo yielding
bar yielding

Try this code:

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();

Couple of footnotes:

  • if you yield a function, it is supposed to be a thunk, that is, it accepts one argument and it is callback;
  • you need to call this callback, it's also a good idea to do that asynchronously;

Applying this your code: - you yield a function, but never call it's cb argument; - the same with next.

vkurchatkin
  • 12,170
  • 2
  • 40
  • 50