javascriptgeneratorco

how to use co.wrap with generator


const co = require('co');

const func1 = function(){
  setTimeout(()=>{
    console.log('func1');
  },2000);
}

const func2 = function(){
  setTimeout(()=>{
    console.log('func2');
  },2000);
}

const func3 = function(){
    console.log('func3');
}

const gen = co.wrap(function*(){
  yield func1;
  yield func2;
  return yield func3;
});


gen()
.then(function(){console.log('end')});

The expected result is func1 func2 func3 end

but it doesn't show what I intended.

It is showing func1

How can I fix the code to output the expected result


Solution

  • Two issues:

    1. There's no way for your functions to return control. If you want to use thunks (which the documentation advises against), you need to actually take and invoke a callback:

      const func1 = function(cb){
        setTimeout(()=>{
          console.log('func1');
      
          return cb();
        },2000);
      };
      

      However, it's better to use promises:

      const func2 = function(){
        return new Promise((resolve) => {
          setTimeout(()=>{
            console.log('func2');
      
            return resolve();
          },2000);
        });
      };
      
    2. If you use promises, you need to invoke the function when you yield it:

      yield func2();
      

      You can only yield a function without calling it if it's a thunk.