如何将 co.wrap 与生成器一起使用

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')});

预期的结果是 功能1 功能2 功能3 结束

但它没有显示我的意图。

正在显示 函数 1

如何修复代码以输出预期结果

两期:

  1. 您的函数无法 return 控制。如果你想使用 thunk(documentation 建议不要使用),你需要实际调用回调:

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

    但是,最好使用 promises:

    const func2 = function(){
      return new Promise((resolve) => {
        setTimeout(()=>{
          console.log('func2');
    
          return resolve();
        },2000);
      });
    };
    
  2. 如果使用promises,yield时需要调用函数:

    yield func2();
    

    你只能 yield 一个函数,如果它是一个 thunk,则不调用它。