forEach循环yield 出错

lamb是一组函数.

const sign = ['red', 'green', 'yellow'];

function tic(str, timer) {
  return () => new Promise((res, rej) => {
    setTimeout(() => {
      console.log(str);
      res();
    }, timer);
  });
}

const lamb = sign.reduce(function (prev, item) {
  prev.push(tic(item, 1000));

  return prev;
}, []);
const gen = function* () {
  lamb.forEach(function (item, index) {
    yield item();
  });

  // for(let i = 0; i < lamb.length; i++) {
  //   yield lamb[i]();
  // }

  //for(let i in lamb) {
    //yield lamb[i]();
//  }
}

为什么 forEach不行(报错Unexpected identifier),for(let i = 0; i < lamb.length; i++) /for(let i in lamb)可以?

阅读 8.9k
4 个回答

注意,forEach里面你是传了一个函数进去,所以你的yield语句实际上在一个不是生成器的函数里面,所以当然报错。

forEach 方法的参数是一个普通函数,里面用yield语句会报错
改用for循环即可

1楼说的对。

lamb.forEach(function (item, index) {

co(function *(yield item()))

});

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题